1 Mybatis映射文件--增刪改查 POJO類 EmployeeMapper.xml IEmployeeDAO 配置文件--log4j.properties 配置文件--db.properties 配置文件--mybatis-config.xml 測試類 ...
1 Mybatis映射文件--增刪改查
- POJO類
package cn.demo1; import org.apache.ibatis.type.Alias; /** * 描述:POJO */ @Alias("emp") public class Employee { private Integer id; private String lastName; private String gender; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", gender='" + gender + '\'' + ", email='" + email + '\'' + '}'; } }
- EmployeeMapper.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="cn.demo1.IEmployeeDAO"> <!-- namespace:命名空間 指定為介面的全類名 id:唯一標識 和介面中的方法名相同 resultType:返回值類型 --> <select id="findById" parameterType="int" resultType="emp" databaseId="mysql"> select id,last_name,email,gender from employee where id = #{id} </select> <insert id="addEmployee" parameterType="cn.demo1.Employee"> insert into employee(last_name,email,gender) values (#{lastName},#{email},#{gender}) </insert> <update id="updateEmployee" parameterType="cn.demo1.Employee"> update employee set last_name = #{lastName} ,email = #{email},gender = #{gender} where id = #{id} </update> <delete id="deleteEmployeeById" parameterType="java.lang.Integer"> delete from employee where id = #{id} </delete> </mapper>
- IEmployeeDAO
package cn.demo1; public interface IEmployeeDAO { public Employee findById(Integer id); public void addEmployee(Employee employee); public void updateEmployee(Employee employee); public void deleteEmployeeById(Integer id); }
- 配置文件--log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
- 配置文件--db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.user=root
jdbc.password=root
- 配置文件--mybatis-config.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> <!-- Mybatis可以使用properties屬性來引入外部properties配置文件內容 resource:引入類路徑下的資源 url:引入網路路徑或磁碟路徑下的資源 --> <properties resource="db.properties"></properties> <settings> <!-- 是否開啟自動駝峰規則映射,即如果數據表中的欄位是last_name到Java中的lastName等類似的映射 --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- typeAliases:別名處理器,可以為Java類型起別名 --> <typeAliases> <!-- 類很多情況下,可以批量設置別名這個包下的每一個類創建一個預設的別名,就是簡單類名小寫。 --> <package name="cn.demo1"/> </typeAliases> <!-- environments ,Mybatis可以配置多種環境 environment,配置一個具體的環境信息,必須有兩個標簽,ID表示當前環境的唯一標識 transactionManager s事務管理器 type 事務管理器的類型 JDBC this.typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class); MANAGER this.typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class); dataSource JNDI this.typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class); POOLED this.typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class); UNPOOLED this.typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class); --> <environments default="mysql_development"> <environment id="mysql_development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> <environment id="oracle_development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${oracle.driver}"/> <property name="url" value="${oracle.url}"/> <property name="username" value="${oracle.user}"/> <property name="password" value="${oracle.password}"/> </dataSource> </environment> </environments> <databaseIdProvider type="DB_VENDOR"> <property name="MySQL" value="mysql"/> <property name="Oracle" value="oracle"/> <property name="SQL Server" value="sqlserver"/> </databaseIdProvider> <mappers> <mapper resource="cn/demo1/EmployeeMapper.xml"/> </mappers> </configuration>
- 測試類
package cn.test; import cn.demo1.Employee; import cn.demo1.IEmployeeDAO; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; /** * * 描述: */ public class MybatisTest { /** * 測試查詢 * @throws IOException */ @Test public void demo1() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class); Employee employee = dao.findById(1); System.out.print(employee); session.close(); } /** * 測試增加 * @throws IOException */ @Test public void demo2() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class); Employee employee = new Employee(); employee.setLastName("呵呵"); employee.setGender("女"); employee.setEmail("[email protected]"); dao.addEmployee(employee); session.commit(); session.close(); } /** * 測試修改 * @throws IOException */ @Test public void demo3() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class); Employee employee = new Employee(); employee.setId(1); employee.setLastName("呵呵"); employee.setGender("女"); employee.setEmail("[email protected]"); dao.updateEmployee(employee); session.commit(); session.close(); } /** * 測試修改 * @throws IOException */ @Test public void demo4() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class); dao.deleteEmployeeById(1); session.commit(); session.close(); } }
2. 主鍵生成方式
2.1 若資料庫支持自動生成主鍵的欄位(比如MySQL和SQLServer),則可以設置unGeneratedKeys="true",然後再把keyProperty設置到目標屬性上。
<insert id="addEmployee" parameterType="cn.demo1.Employee" useGeneratedKeys="true" keyProperty="id"> insert into employee(last_name,email,gender) values (#{lastName},#{email},#{gender}) </insert>
package cn.demo1; import org.apache.ibatis.type.Alias; /** * 描述:POJO */ @Alias("emp") public class Employee { private Integer id; private String lastName; private String gender; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", gender='" + gender + '\'' + ", email='" + email + '\'' + '}'; } }
package cn.demo1; public interface IEmployeeDAO { public Employee findById(Integer id); public void addEmployee(Employee employee); public void updateEmployee(Employee employee); public void deleteEmployeeById(Integer id); }
<?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="cn.demo1.IEmployeeDAO"> <!-- namespace:命名空間 指定為介面的全類名 id:唯一標識 和介面中的方法名相同 resultType:返回值類型 --> <select id="findById" parameterType="int" resultType="emp" databaseId="mysql"> select id,last_name,email,gender from employee where id = #{id} </select> <insert id="addEmployee" parameterType="cn.demo1.Employee" useGeneratedKeys="true" keyProperty="id"> insert into employee(last_name,email,gender) values (#{lastName},#{email},#{gender}) </insert> <update id="updateEmployee" parameterType="cn.demo1.Employee"> update employee set last_name = #{lastName} ,email = #{email},gender = #{gender} where id = #{id} </update> <delete id="deleteEmployeeById" parameterType="java.lang.Integer"> delete from employee where id = #{id} </delete> </mapper>
<?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> <!-- Mybatis可以使用properties屬性來引入外部properties配置文件內容 resource:引入類路徑下的資源 url:引入網路路徑或磁碟路徑下的資源 --> <properties resource="db.properties"></properties> <settings> <!-- 是否開啟自動駝峰規則映射,即如果數據表中的欄位是last_name到Java中的lastName等類似的映射 --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- typeAliases:別名處理器,可以為Java類型起別名 --> <typeAliases> <!-- 類很多情況下,可以批量設置別名這個包下的每一個類創建一個預設的別名,就是簡單類名小寫。 --> <package name="cn.demo1"/> </typeAliases> <!-- environments ,Mybatis可以配置多種環境 environment,配置一個具體的環境信息,必須有兩個標簽,ID表示當前環境的唯一標識 transactionManager s事務管理器 type 事務管理器的類型 JDBC this.typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class); MANAGER this.typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class); dataSource JNDI this.typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class); POOLED this.typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class); UNPOOLED this.typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class); --> <environments default="mysql_development"> <environment id="mysql_development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> <environment id="oracle_development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${oracle.driver}"/> <property name="url" value="${oracle.url}"/> <property name="username" value="${oracle.user}"/> <property name="password" value="${oracle.password}"/> </dataSource> </environment> </environments> <databaseIdProvider type="DB_VENDOR"> <property name="MySQL" value="mysql"/> <property name="Oracle" value="oracle"/> <property name="SQL Server" value="sqlserver"/> </databaseIdProvider> <mappers> <mapper resource="cn/demo1/EmployeeMapper.xml"/> </mappers> </configuration>
/** * 測試增加 * @throws IOException */ @Test public void demo2() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); IEmployeeDAO dao = session.getMapper(IEmployeeDAO.class); Employee employee = new Employee(); employee.setLastName("呵呵"); employee.setGender("女"); employee.setEmail("[email protected]"); dao.addEmployee(employee); System.out.print(employee.getId()); session.commit(); session.close(); }
2.2 對於不支持自增主鍵的資料庫,則可以使用selectKey子元素;selectKey元素將會首先運行,id會被設置,後插入語句會被調用。
<insert id="addEmployee" parameterType="cn.demo1.Employee" databaseId="oracle"> <selectKey order="BEFORE" keyProperty="id" resultType="java.lang.Integer"> select employee_seq.nextval from dual; </selectKey> insert into employee(id,last_name,email,gender) values (#{id},#{lastName},#{email},#{gender}) </insert>
3 參數傳遞
- 單個參數:
- 可以接受基本類型,對象類型,集合類型的值。這種情況可直接使用這個參數,不需要經過任何處理。
- 多個參數:
- 任意多個參數,都會被Mybatis重新包裝成一個Map傳入。Map的key是param1,param2,0,1...值就是參數的值。
- 命名參數:
- 為參數使用@param起一個名字,Mybatis就會將這些參數封裝到map中,key就是我們自己指定的名字。
- POJO:
- 當這些參數屬於業務的POJO的時候,我們直接傳遞POJO。#{屬性值}中的屬性值為POJO的屬性值。
- Map:
- 我們也可以封裝多個參數為map,直接傳遞。
- 註意:
- 如果是Collection類型的話,那麼key是collection。
- 如果是List類型的話,那麼key是list。
- 如果是數組的話,那麼key是array。