properties
这个properties是外部化可替代属性的配置,在里面是存放的键值对,我这里举例说明
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/happ
username=root
password=123456
id=3
- 这里面存放的就是我们连接池 的键值对,我们到时候就可以直接使用
- 同时这也是共享的
MybatisMainCof.xml
<configuration>
<properties resource="db.properties">
<property name="id" value="2"/>
</properties>
<typeAliases>
<typeAlias type="domain.User" alias="user"/>
</typeAliases>
<environments default="development">
<!-- 可以配置多个environment -->
<environment id="development">
<!-- 每个environment对应一个sqlSession,用id进行区分 -->
<!-- 配置事务 -->
<transactionManager type="JDBC" />
<!-- 配置数据源信息 -->
<dataSource type="POOLED"> <!-- 连接池 -->
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- 映射到具体的配置文件 -->
<mappers>
<mapper resource="UserMapper.xml"/>
<mapper resource="JoinMapper.xml"/>
<mapper class="dao.UserDao"/>
</mappers>
</configuration>
- 这里我们需要注意配置的位置
- properties是配置再configuration里面,而不是其他地方哦
- 然后注意我们数据源里面使用的就是键值对的键值,这样就可以直接完成配置了
properties其他作用
-
上面我们已经介绍了一种用法,配置我们的数据源
-
然而第二个作用就可以用于参数的传递,但是我们需要注意优先级
<properties resource="db.properties"> <property name="id" value="2"/> </properties> Properties prop=new Properties(); prop.put("id","4"); SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is,prop); db.properties(属性文件)
-
以上三种方式都可以存放键值对,但是有使用优先级
-
第二种方法记住,如果用了需要加载进去
-
优先级顺序:参数传递>属性文件>属性项
-
使用方法注意是:${} 而不是#{}
<select id="findById" parameterType="int" resultType="user"> <include refid="selectId"/> tb_user where id=${id} </select>
Mapper
Mapper的作用我们都知道就是映射到我们各自的资源文件,我们前面了解两种方法
- resource
- class
这里的第一种方法我们都知道,就是填写我们的资源类
下面介绍第二种方法
class
- 这里两点注意事项:
- 1.使用class配置
- 2.xml文件和接口类必须放在同一个包下,并且同名
typeAliases
这个是别名的属性,我们一般的实体类的包名很长,是域名的到写,所以我们可以使用别名替代
这就是最简单的一个应用,仅仅是用来替代别名的作用而已
constructor(构造器)
<resultMap type="domain.User" id="UserMap">
<constructor>
<idArg column="id" javaType="String"/>
<arg column="username" javaType="String"/>
<arg column="password" javaType="String"/>
</constructor>
</resultMap>
-
这里大家看见resultMap应该也知道这个是写在那里面的吧
-
这个的用法主要是有别名的时候使用,一般使用不多
<select id="findById" parameterType="int" resultMap="UserMap"> select * from tb_user where id=#{id} </select>
使用的时候直接使用Map的id便可