數據庫:
依賴:
<dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.3</version> </dependency> <!--junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.10.RELEASE</version> </dependency> </dependencies>
相關配置文件:
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> </configuration>
log4j.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration > <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <param name="Encoding" value="UTF-8"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/> </layout> </appender> <logger name="java.sql"> <level value="debug"/> </logger> <logger name="org.apache.ibatis"> <level value="info"/> </logger> <root> <level value="debug"/> <appender-ref ref="STDOUT"/> </root> </log4j:configuration>
db.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://xxx.xx.xxx.xxx:3306/mp?useUnicode=true&characterEncoding=UTF8 jdbc.username=root jdbc.password=123456
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 數據源 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 事務管理器 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 基於注解的事務管理 --> <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/> <!-- 配置 SqlSessionFactoryBean mybatis提供的:org.mybatis.spring.SqlSessionFactoryBean mybatisplus提供的:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean --> <bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <!-- 數據源 --> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 別名處理 --> <property name="typeAliasesPackage" value="com.ytkj.mybatisplus.entity"></property> <!--注入全局mybatisplus策略配置--> <property name="globalConfig" ref="globalConfiguration"></property> </bean> <!-- 配置 mybatis 掃描 mapper 接口的路徑 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ytkj.mybatisplus.mapper"></property> </bean> <!--定義mybatisplus的全局策略配置 --> <bean id="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!--實體類下划線轉駝峰--> <property name="dbColumnUnderline" value="true"></property> <!--配置全局id自增長策略--> <property name="idType" value="0"></property> <!--全局的表前綴配置--> <property name="tablePrefix" value="tbl_"></property> </bean> </beans>
entity:
package com.ytkj.mybatisplus.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.enums.IdType; /** * javaBean * 定義javaBean中成員變量時所使用的類型 */ /** * @TableName: * value:數據庫表名 * */ @TableName(value ="tbl_employee" ) public class Employee { /*id INT(11) PRIMARY KEY AUTO_INCREMENT, last_name VARCHAR(50), email VARCHAR(50), gender CHAR(1), age INT*/ /** * @TableId: * value:指定表中的主鍵列的列名,如果實體屬性名與列名一致可以省略 * type:指定主鍵策略 * */ @TableId(value = "id",type = IdType.AUTO) @TableField( value = "id",exist = true) private Integer id; @TableField(value = "last_name",exist = true) private String lastName; @TableField(value = "email",exist = true) private String email; @TableField(value = "gender",exist =true) private Integer gender; @TableField(value ="age",exist = true) private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", gender=" + gender + ", age=" + age + '}'; } }
Mapper:
package com.ytkj.mybatisplus.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.ytkj.mybatisplus.entity.Employee; /** * mapper接口 * :基於mybatis:在Mapper接口中編寫CRUD相關方法,提供Mapper接口所對應的SQL映射文件一級方法對應的SQL語句 * :基於mybatisplus:讓xxxMapper接口繼承baseMapper<T>即可,T指定的就是當前mapper接口所操作的實體類類型 */ public interface EmployeeMapper extends BaseMapper<Employee> { }
Test:
基本增刪改查
package junit.test; import com.baomidou.mybatisplus.plugins.Page; import com.ytkj.mybatisplus.entity.Employee; import com.ytkj.mybatisplus.mapper.EmployeeMapper; import org.apache.ibatis.session.RowBounds; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestMybatisPlus { private ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void testDataSource() throws SQLException { DataSource dataSource=ioc.getBean("dataSource",DataSource.class); System.out.println(dataSource); Connection connection = dataSource.getConnection(); System.out.println(connection); } /** * 從容器中獲取employeeMapper */ private EmployeeMapper employeeMapper=ioc.getBean("employeeMapper",EmployeeMapper.class); /** * 通用插入操作 插入實體類設置值的字段,只有非空的屬性對應的字段才會出現到SQL語句中 * INSERT INTO tbl_employee ( last_name, age ) VALUES ( ?, ? ) */ @Test public void testInsert(){ Employee employee=new Employee(); employee.setLastName("zhechaochao"); employee.setAge(18); Integer row = employeeMapper.insert(employee); System.out.println("row="+row); //獲取數據庫中的主鍵值 Integer id = employee.getId(); System.out.println(id); } /** * 通用插入操作 插入時不管屬性是否非空,屬性所對應的字段都會出現到SQL語句中 * INSERT INTO tbl_employee ( last_name,email,gender,age ) VALUES ( ?,?,?,? ) */ @Test public void testInsertAllColumn(){ Employee employee=new Employee(); employee.setLastName("zhechaochao"); employee.setAge(18); Integer row = employeeMapper.insertAllColumn(employee); System.out.println("row="+row); //獲取數據庫中的主鍵值 Integer id = employee.getId(); System.out.println(id); } /** * 根據id更新 * UPDATE tbl_employee SET gender=?, age=? WHERE id=? */ @Test public void testUpdateById(){ Employee employee=new Employee(); employee.setId(7); employee.setGender(1); employee.setAge(25); Integer row = employeeMapper.updateById(employee); System.out.println("row="+row); } /** * 根據id更新 * 慎用,更新所有字段 其他字段原本有值會被設置為null * UPDATE tbl_employee SET last_name=?,email=?,gender=?,age=? WHERE id=? */ @Test public void testUpdateAllColumnById(){ Employee employee=new Employee(); employee.setId(7); employee.setGender(1); employee.setAge(25); Integer row = employeeMapper.updateAllColumnById(employee); System.out.println("row="+row); } /** * 更具id查詢 * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id=? */ @Test public void testSelectById(){ Employee employee = employeeMapper.selectById(1); System.out.println(employee); } /** *通過多列進行查詢 id+lastName * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id=? AND last_name=? */ @Test public void testSelectOne(){ Employee employee=new Employee(); employee.setId(6); employee.setLastName("zhechaochao"); Employee employee1 = employeeMapper.selectOne(employee); System.out.println(employee1); } /** *根據id批量查詢 * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id IN ( ? , ? , ? ) */ @Test public void testSelectBatchIds(){ List<Integer> list=new ArrayList<>(); list.add(1); list.add(2); list.add(6); List<Employee> employees = employeeMapper.selectBatchIds(list); System.out.println(employees); } /** *通過map封裝查詢條件 * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE gender = ? AND last_name = ? AND id = ? */ @Test public void testSelectByMap(){ Employee employee=new Employee(); Map<String,Object> map=new HashMap<>(); /** * put時是數據庫中的列名而不是實體類的屬性名 */ map.put("id",1); //map.put("lastName","Tom");報錯 map.put("last_name","Tom"); map.put("gender",1); List<Employee> employees = employeeMapper.selectByMap(map); System.out.println(employees); } /** *不根據條件分頁查詢 * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee */ @Test public void testSelectPage(){ RowBounds rowBounds=new RowBounds(0,2); List<Employee> employees = employeeMapper.selectPage(rowBounds, null); System.out.println("employees"+employees); Page<Employee> page=new Page<>(0,2); List<Employee> employees1 = employeeMapper.selectPage(page, null); System.out.println("employees1"+employees1); } /** *根據id刪除 * DELETE FROM tbl_employee WHERE id=? */ @Test public void testDeleteById(){ Integer row = employeeMapper.deleteById(7); System.out.println("row"+row); } /** *根據id批量刪除 * DELETE FROM tbl_employee WHERE id IN ( ? , ? ) */ @Test public void testDeleteBatchIds(){ List<Integer> list=new ArrayList<>(); list.add(8); list.add(9); Integer row = employeeMapper.deleteBatchIds(list); System.out.println("row"+row); } /** *通過map封裝刪除條件 * DELETE FROM tbl_employee WHERE last_name = ? AND id = ? AND age = ? */ @Test public void testDeleteByMap(){ Map<String,Object> map=new HashMap<>(); map.put("id",6); map.put("last_name","zhechaochao"); map.put("age",18); Integer row = employeeMapper.deleteByMap(map); System.out.println("row"+row); } }
條件構造器刪改查
package junit.test; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.ytkj.mybatisplus.entity.Employee; import com.ytkj.mybatisplus.mapper.EmployeeMapper; import org.apache.ibatis.session.RowBounds; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestMybatisPlusConditionalQuery { private ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void testDataSource() throws SQLException { DataSource dataSource=ioc.getBean("dataSource",DataSource.class); System.out.println(dataSource); Connection connection = dataSource.getConnection(); System.out.println(connection); } /** * 從容器中獲取employeeMapper */ private EmployeeMapper employeeMapper=ioc.getBean("employeeMapper",EmployeeMapper.class); /** * 條件構造器 查詢操作 * 年齡在 18~50 之間性別為男且姓名為 xx 的所有用戶 *SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (age BETWEEN ? AND ? AND gender = ? AND last_name = ?) */ @Test public void testSelectPage(){ Page<Employee> page=new Page<>(0,2); EntityWrapper<Employee> entityWrapper=new EntityWrapper<>(); entityWrapper.between("age",18,50).eq("gender",1).eq("last_name","Tom"); List<Employee> list = employeeMapper.selectPage(page, entityWrapper); System.out.println(list); } /** * 條件構造器 查詢操作 * 性別為女並且名字中帶有laoshi或者郵箱中帶有a *or()===>SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (gender = ? AND last_name LIKE ? OR email LIKE ?) * orNew()===>SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (gender = ? AND last_name LIKE ?) OR (email LIKE ?) * */ @Test public void testSelectList(){ EntityWrapper<Employee> entityWrapper=new EntityWrapper<>(); //entityWrapper.eq("gender",0).like("last_name","laoshi").or().like("email","a"); entityWrapper.eq("gender",0).like("last_name","laoshi").orNew().like("email","a"); List<Employee> employees = employeeMapper.selectList(entityWrapper); System.out.println(employees); } /** * 條件構造器 查詢操作 * 名字為Tom性別為男根據年齡排序 * SELECT id AS id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE (gender = ? AND last_name = ?) ORDER BY age DESC * */ @Test public void testSelectList2(){ EntityWrapper<Employee> entityWrapper=new EntityWrapper<>(); entityWrapper.eq("gender",1).eq("last_name","Tom").orderBy("age",false); List<Employee> employees = employeeMapper.selectList(entityWrapper); System.out.println(employees); } /** * 條件構造器 查詢操作 * 根據名字長度大於10分組 * 更具性別分組,查詢每組的平均年齡,最大年齡,最小年齡。並且只取平均年齡大於21的組 * SELECT MAX(age),MIN(age),AVG(age) FROM tbl_employee GROUP BY gender HAVING (avg(age)>21) */ @Test public void testSelectMaps(){ EntityWrapper<Employee> entityWrapper=new EntityWrapper<>(); entityWrapper.setSqlSelect("MAX(age),MIN(age),AVG(age)").groupBy("gender").having("avg(age)>21"); List<Map<String, Object>> list = employeeMapper.selectMaps(entityWrapper); list.forEach(System.out::println); } /** * 條件構造器 修改操作 *名字為xiaohong並且性別為女年齡為10的人名字改為honghonglaoshi,郵箱改為120@qq.com * UPDATE tbl_employee SET last_name=?, email=? WHERE (last_name = ? AND gender = ? AND age = ?) */ @Test public void testUpdate(){ Employee employee=new Employee(); employee.setLastName("honghonglaoshi"); employee.setEmail("120@qq.com"); EntityWrapper<Employee> entityWrapper=new EntityWrapper<>(); entityWrapper.eq("last_name","xiaohong").eq("gender",0).eq("age",10); Integer row = employeeMapper.update(employee, entityWrapper); System.out.println(row); } /** * 條件構造器 刪除操作 *刪除名字為Tom並且性別為女年齡為45 *DELETE FROM tbl_employee WHERE (last_name = ? AND gender = ? AND age = ?) */ @Test public void testDelete(){ EntityWrapper<Employee> entityWrapper=new EntityWrapper<>(); entityWrapper.eq("last_name","Tom").eq("gender",0).eq("age",45); Integer row = employeeMapper.delete(entityWrapper); System.out.println(row); } }