Mybatis—XML配置
一.数据库配置
由于Mybatis需要与数据库通信,因此必须配置数据库的详细信息,代码如下:
<configuration>
<environments default = "development">
<environment id = "development">
<transactionManager type = "JDBC"/>
<dataSource type = "POOLED">
<property name = "driver" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/"/>
<property name = "username" value = "root"/>
<property name = "password" value = "123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="User.xml"/>
</mappers>
</configuration>
-
environments:
数据库环境,可以通过配置多个environments来连接到多个数据库。 -
transactionManager:
事务管理器,MyBatis支持两个事务管理器,即JDBC和MANAGED,使用JDBC的事务管理机制,就是利用java.sql.Connection对象完成对事务的提交,Mybatis提供了一个事务接口Transaction,以及两个实现类jdbcTransaction和ManagedTransaction;MANAGED这种机制mybatis自身不会去实现事务管理,而是让程序的容器来实现对事务的管理。 -
dataSource:
数据库连接属性,POOLED表示MyBatis将维护数据库连接池,并且对于每个数据库操作,MyBatis都使用连接池中的一个连接,完成操作后再返回到池中。 -
mappers:
用于在MyBatis的配置文件中配置映射器xml文件的位置。
二.Mapper配置
Mapper XML包含一组用于配置各种SQL语句的语句,如select,insert,update和delete,所有语句都有唯一的ID,代码如下:
<mapper namespace="com.mybatis.demo">
<select id="getUser" resultType="com.mybatis.demo.User">
SELECT * FROM tabuser
<where>
<if test="_parameter != null">
Id = #{id}
</if>
</where>
</select>
</mapper>
- id:
sql语句的唯一标识符,同时parametertype也是传递给语句参数的类名或别名。如下:
<insert id = "insert" parameterType = "User">
insert into tabuser (name, age ) values (#{name}, #{age});
</insert>
- resultMaps:
resultMaps用于SELECT语句结果映射到Java bean,一旦定义了结果映射,select都可以调用,如下:
<resultMap id = "result" type = "User">
<result property = "id" column = "ID"/>
<result property = "name" column = "NAME"/>
<result property = "age" column = "age"/>
</resultMap>
<select id = "getAllUsers" resultMap = "result">
SELECT * FROM tabuser;
</select>
<select id = "getUserById" parameterType = "int" resultMap = "result">
SELECT * FROM tabuser WHERE ID = #{id};
</select>