鳴謝:http://my.oschina.net/u/1763011/blog/324106?fromerr=nJakGh4P (也可參看此博客進行配置)
http://www.cnblogs.com/zcy_soft/p/3358132.html(補充1)
http://blog.csdn.net/sunny243788557/article/details/45166397 (補充2)
http://www.cnblogs.com/yjmyzz/p/4210554.html (補充3)
http://www.myexception.cn/software-architecture-design/621662.html (補充4)
http://mbg.cndocs.tk (MyBatis Generator介紹)
http://blog.csdn.net/isea533/article/details/42102297 (MyBatis Generator詳解)
http://www.cnblogs.com/daxin/p/3545040.html (Mybatis MapperScannerConfigurer 自動掃描 將Mapper接口生成代理注入到Spring)
---------------------------------------------------------------------------------------------------------------------------
測試項目:Test
1.新建maven項目
2.pom.xml文件中添加插件,如:
<build> <finalName>org.zsl.hnust</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build>
3.在項目的/src/main/resources(默認目錄)的文件目錄下加入generateConfig.xml
如:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <classPathEntry location="D:\repo\mysql-connector-java-5.1.26.jar" /> <context id="context1" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自動生成的注釋 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="" /> <javaModelGenerator targetPackage="com.cn.hnust.pojo" targetProject="D:\Eclipse_Workspace\HNUST\org.zsl.hnust Maven Webapp\src\main\java" /> <sqlMapGenerator targetPackage="com.cn.hnust.mapping" targetProject="D:\Eclipse_Workspace\HNUST\org.zsl.hnust Maven Webapp\src\main\java" /> <javaClientGenerator type="XMLMAPPER" targetPackage="com.cn.hnust.dao" targetProject="D:\Eclipse_Workspace\HNUST\org.zsl.hnust Maven Webapp\src\main\java"> </javaClientGenerator> <table tableName="t_student" domainObjectName="Address" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" > <property name="useActualColumnNames" value="true"/> </table> </context> </generatorConfiguration>
注:
javaModelGenerator :指定生成pojo的包和此包在項目中的地址;
sqlMapGenerator :指定生成pojo的映射xml文件的所在包和此包在項目中的地址;
javaClientGenerator :指定生成訪問映射xml文件的接口所在包和此包在項目中的地址;
table屬性:
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"
schema為數據庫名, tableName為對應的數據庫表, domainObjectName是要生成的實體類,
如果想要mapper配置文件加入sql的where條件查詢, 可以將enableCountByExample等設為true,
這樣就會生成一個對應domainObjectName的Example類, enableCountByExample等設為false時,
就不會生成對應的Example類了.
如果table里邊不配置property,默認字段都生成為類屬性。
<ignoreColumn column="FRED" />//忽略字段
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />//無論字段是什么類型,生成的類屬性都是varchar。
4.項目 右鍵--》run as --》 maven bulid --》彈出對話框 --》在goals中輸入mybatis-generator:generate (或者 點擊select --》選擇你的mybatis插件 --》apply --》run)
5:選擇項目 按 F5 刷新項目 出現生成的代碼。
說明:上面示例的generateConfig.xml 可簡化成以下寫法:即把targetProject的決定路徑改為項目中的相對路徑。以后要用可直接復制下面的。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <classPathEntry location="D:\repo\mysql-connector-java-5.1.26.jar" /> <context id="context1" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自動生成的注釋 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="" /> <javaModelGenerator targetPackage="com.cn.hnust.pojo" targetProject="src/main/java" /> <sqlMapGenerator targetPackage="sqlMap" targetProject="src/main/resources" /> <javaClientGenerator type="XMLMAPPER" targetPackage="com.cn.hnust.dao" targetProject="src/main/java"> </javaClientGenerator> <table tableName="t_student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" > <property name="useActualColumnNames" value="true"/> </table> </context> </generatorConfiguration>
值得注意的是pojo映射文件的存放地址在項目中要記得配對哦,如:
spring-mybatis.xml中下面的配置:這里sql映射文件存放在src/main/resources目錄
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 原:value="classpath:com/cn/hnust/mapping/*.xml"--> <property name="mapperLocations" value="classpath:sqlMap/*.xml"/> </bean>
sql映射文件存放地址:
實踐:
1.建表 t_student
2.項目 右鍵--》run as --》 maven bulid 生成代碼(按上面簡化的generateConfig.xml)
3.查看生成的代碼
a.Student.java 略
b.StudentMapper 注意:1.訪問pojo的映射文件可直接通過此接口訪問,不需要建立實現類。2.在spring-mybatis.xml中MapperScannerConfigurer會把sqlSessionFactory注入此類,所以也不需要注入sqlSessionFactory、SqlSessionTemplate 。具體參見:http://www.cnblogs.com/daxin/p/3545040.html
package com.cn.hnust.dao; import com.cn.hnust.pojo.Student; public interface StudentMapper { int deleteByPrimaryKey(Integer sid); int insert(Student record); int insertSelective(Student record); Student selectByPrimaryKey(Integer sid); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record); }
c.StudentMapper.xml
<?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="com.cn.hnust.dao.StudentMapper" > <resultMap id="BaseResultMap" type="com.cn.hnust.pojo.Student" > <id column="sid" property="sid" jdbcType="INTEGER" /> <result column="sname" property="sname" jdbcType="VARCHAR" /> <result column="sex" property="sex" jdbcType="CHAR" /> </resultMap> <sql id="Base_Column_List" > sid, sname, sex </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from t_student where sid = #{sid,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from t_student where sid = #{sid,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.cn.hnust.pojo.Student" > insert into t_student (sid, sname, sex) values (#{sid,jdbcType=INTEGER}, #{sname,jdbcType=VARCHAR}, #{sex,jdbcType=CHAR}) </insert> <insert id="insertSelective" parameterType="com.cn.hnust.pojo.Student" > insert into t_student <trim prefix="(" suffix=")" suffixOverrides="," > <if test="sid != null" > sid, </if> <if test="sname != null" > sname, </if> <if test="sex != null" > sex, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="sid != null" > #{sid,jdbcType=INTEGER}, </if> <if test="sname != null" > #{sname,jdbcType=VARCHAR}, </if> <if test="sex != null" > #{sex,jdbcType=CHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.cn.hnust.pojo.Student" > update t_student <set > <if test="sname != null" > sname = #{sname,jdbcType=VARCHAR}, </if> <if test="sex != null" > sex = #{sex,jdbcType=CHAR}, </if> </set> where sid = #{sid,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.cn.hnust.pojo.Student" > update t_student set sname = #{sname,jdbcType=VARCHAR}, sex = #{sex,jdbcType=CHAR} where sid = #{sid,jdbcType=INTEGER} </update> </mapper>
4.測試
package org.zsl.testmybatis; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.cn.hnust.dao.StudentMapper; import com.cn.hnust.pojo.Address; import com.cn.hnust.pojo.Student; @RunWith(SpringJUnit4ClassRunner.class) //表示繼承了SpringJUnit4ClassRunner類 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class StudentTest { @Resource private StudentMapper studentMapper; @Test public void insert(){ Student s = new Student(); s.setSex("女"); s.setSname("李浩"); studentMapper.insert(s); } @Test public void deleteByPrimaryKey(){ studentMapper.deleteByPrimaryKey(1); } @Test public void insertSelective(){ Student s = new Student(); s.setSname("李浩"); studentMapper.insertSelective(s); } @Test public void selectByPrimaryKey(){ Student s = studentMapper.selectByPrimaryKey(2); System.out.println(s); } @Test public void updateByPrimaryKeySelective(){ Student s = studentMapper.selectByPrimaryKey(2); s.setSname("張三"); studentMapper.updateByPrimaryKeySelective(s); } @Test public void updateByPrimaryKey(){ Student s = studentMapper.selectByPrimaryKey(2); s.setSname("王五"); s.setSex("男"); studentMapper.updateByPrimaryKeySelective(s); } }
附:
spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動掃描 --> <context:component-scan base-package="com.cn.hnust" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化連接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 連接池最大數量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 連接池最大空閑 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 連接池最小空閑 --> <property name="minIdle" value="${minIdle}"></property> <!-- 獲取連接最大等待時間 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 原:value="classpath:com/cn/hnust/mapping/*.xml"--> <property name="mapperLocations" value="classpath:sqlMap/*.xml"/> </bean> <!-- DAO接口所在包名,Spring會自動查找其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cn.hnust.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
項目結構: