Mybatis基本配置與執行
阿新 • • 發佈:2019-02-09
Mybatis對資料庫的操作都是寫在xml檔案中的,因此Configuration.xml非常重要,以下是一段事例程式碼:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/wechat?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root"/>
<property name="password" value="1"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/config/sql/User.xml"/>
</mappers>
</configuration>
很明顯,前面就是JDBC的驅動,使用者名稱,密碼資訊,<mappers>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Message">
<resultMap type="com.bean.Message" id="MessageResult">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="COMMAND" jdbcType="VARCHAR" property="command"/>
<result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
<result column="CONTENT" jdbcType="VARCHAR" property="content"/>
</resultMap>
<select id="queryMessage" parameterType="com.bean.Message" resultMap="MessageResult">
select * from message where 1=1
<if test="command != null and !"".equals(command.trim())">
and COMMAND=#{command}
</if>
<if test="description != null and !"".equals(description.trim())">
and DESCRIPTION like '%' #{description} '%'
</if>
</select>
</mapper>
- resultMap標籤就是資料庫資料與JavaBean實體類的對映關係,內部分為表示主鍵的id標籤和普通的result便籤,jdbcType是與jdbc相對應的資料型別
- select標籤是要執行的select sql語句放的地方,類似的還有delete,insert,update標籤,每個sql語句都有一個唯一的ID供邏輯層呼叫
整體感覺跟Hibernate的配置很相似,後面繼續學習Sql語句的拼接