《Java EE核心框架实战》—— 2.2 连接DB数据库的参数来自于Properties对象

    xiaoxiao2024-04-17  106

    本节书摘来异步社区《Java EE核心框架实战》一书中的第2章,第2.2节,作者: 高洪岩,更多章节内容可以访问云栖社区“异步社区”公众号查看。

    2.2 连接DB数据库的参数来自于Properties对象

    在前面的示例中,连接数据库时的具体参数是直接在mybatis-config.xml文件中进行定义的,比如url.username和password这些信息。MyBatis还支持将这些参数值写入*.properties属性文件中。

    更改mybatis-config.xml配置文件的部分代码如下。

    <dataSource type="POOLED"> <property name="driver" value="${drivername}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource>``` 在src中创建db.properties属性文件,内容如下。

    url=jdbc:sqlserver://localhost:1079;databaseName=ghydbdrivername=com.microsoft.sqlserver.jdbc.SQLServerDriverusername=sapassword=`使用如下Java代码即可进行数据库的操作:

    InputStream isRef = GetSqlSession.class .getResourceAsStream("/db.properties"); Properties prop = new Properties(); prop.load(isRef); String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream, prop); SqlSession sqlSsession = sqlSessionFactory.openSession();```
    最新回复(0)