MyBatisPlus学習ノート(一)Mapper CRUDインタフェースWrapper条件コンストラクタ

48925 ワード

MyBatisPlus学習ノート(一)Mapper CRUDインタフェースWrapper条件コンストラクタ
文書ディレクトリ
  • MyBatisPlus学習ノート(一)Mapper CRUDインタフェースWrapper条件コンストラクタ
  • Mapper CRUDインタフェース
  • 基礎構成
  • データベースが正常に接続されたかどうかを確認する
  • 汎用CRUD
  • 汎用CRUD insert
  • 汎用CRUD update
  • 汎用CRUD select
  • 汎用CRUD delete
  • 条件コンストラクタ(Wrapper)
  • 条件コンストラクタupdate
  • 条件コンストラクタselect
  • 条件コンストラクタdelete
  • Mapper CRUDインタフェース
    基本構成
  • 以下のすべての方法は、この基礎の下で
  • に確立されている.
  • public class TestMP {
    	
    	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    	
    	EmployeeMapper empMapper = applicationContext.getBean("employeeMapper", EmployeeMapper.class);
        // ...
    }
    
  • applicationContext.xml
    
    <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.user}">property>
    		<property name="password" value="${jdbc.password}">property>
    	bean>
    	
    	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<property name="dataSource" ref="dataSource">property>
    	bean>
    	
    	<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
    	
    	
    	<bean id="sqlSessionFactory" 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.fu.bean">property>		
    		
    		
    		<property name="globalConfig" ref="globalConfiguration">property>
    	bean>
    	
    	
    	
    		
    		<property name="dbColumnUnderline" value="true">property>
    		
    		
    		<property name="idType" value="0">property>
    		
    		
    		<property name="tablePrefix" value="tbl_">property>
    	bean>
    	
    	
    	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<property name="basePackage" value="com.fu.mapper">property>
    	bean>
    beans>
    
  • mybatis-config.xml
    
    
    	
    <configuration>
    configuration>
    
  • db.properties
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/xxx
    jdbc.user=xxx
    jdbc.password=xxx
    #  xxx       
    
  • log4j.xml
    
    
     
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
     
     <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) 
    "
    />
    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>

  • データベースが正常に接続されていることを確認
  • @Test
    public void testDatasource() throws SQLException {
        DataSource sd = applicationContext.getBean("dataSource", DataSource.class);
        System.out.println(sd);
        Connection connection = sd.getConnection();
        System.out.println(connection);
    }
    //     com.mchange.v2.c3p0.impl.NewProxyConnection@353352b6 [wrapping: com.mysql.jdbc.JDBC4Connection@4681c175]        
    

  • 汎用CRUD
    汎用CRUD insert
    public void testInsertAllColumn() {
        Employee employee = new Employee();
        employee.setLastName("efda");
        // insert      ,                  ,                 SQL   
        Integer result = empMapper.insertAllColumn(employee);
        // INSERT INTO tbl_employee ( last_name,email,gender,age ) VALUES ( ?,?,?,? )
    
        // insertAllColumn      ,         ,              SQL   
        //		Integer insert = empMapper.insert(employee);
        // INSERT INTO tbl_employee ( last_name ) VALUES ( ? )
        System.out.println("result="+result);
    
        //               
        Integer key = employee.getId();
        System.out.println("key:" + key );
    }
    

    汎用CRUD update
    public void testUpdate() {
        Employee employee = new Employee();
        employee.setLastName("az");
        employee.setAge(24);
        employee.setGender(1);
        employee.setId(4);
    
        //		Integer update = empMapper.updateById(employee);
        // UPDATE tbl_employee SET last_name=?, gender=?, age=? WHERE id=? 
    
        //		Integer update = empMapper.updateAllColumnById(employee);
        // UPDATE tbl_employee SET last_name=?,email=?,gender=?,age=? WHERE id=?
    
        String setSql = "age = 18 where id = 5";
        Integer update = empMapper.updateForSet(setSql, null);
        // UPDATE tbl_employee SET age = 18 where id = 5
        System.out.println("update="+update);
    }
    

    汎用CRUD select
    	public void testSelect() {
    		// 1.   id  
    //		Employee employee = empMapper.selectById(2);
    		// SELECT id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id=?
    //		System.out.println(employee);
    		
    		//2.     id        
    //		List ids = new ArrayList<>();
    //		ids.add(1);
    //		ids.add(2);
    //		ids.add(3);
    //		ids.add(4);
    //		List list = empMapper.selectBatchIds(ids);
    //		//  SELECT id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE id IN ( ? , ? , ? , ? )
    //		System.out.println(list);
    		
    		//3.              age  +  lastName
    		//           ,        
    //		Employee employee = new Employee();
    //		employee.setLastName("qaaz");
    //		employee.setAge(18);
    //		Employee employeeOne = empMapper.selectOne(employee);
    //		// SELECT id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE last_name=? AND age=?
    //		System.out.println(employeeOne);
    		
    		
    		//4.   Map      
    //		Map map = new HashMap<>();
    //		map.put("last_name", "az");
    //		map.put("gender", 1);
    //		List list = empMapper.selectByMap(map);
    		// SELECT id,last_name AS lastName,email,gender,age FROM tbl_employee WHERE gender = ? AND last_name = ?
    		
    		//5.     
    		//    ,    ,      ,          
    		List<Employee> list = empMapper.selectPage(new Page<>(2,3), null);
    		// SELECT id,last_name AS lastName,email,gender,age FROM tbl_employee
    		System.out.println(list);
    		
    	}
    

    汎用CRUD delete
    	public void testDelete() {
    		// 1.   id  
    //		Integer result = empMapper.deleteById(1);
    		// DELETE FROM tbl_employee WHERE id=?
    		
    		//2.     id    
    //		List ids = new ArrayList<>();
    //		ids.add(1);
    //		ids.add(2);
    //		ids.add(3);
    //		Integer result = empMapper.deleteBatchIds(ids);
    		// DELETE FROM tbl_employee WHERE id IN ( ? , ? , ? )
    		
    		//3.   Map      
    		//              
    		Map<String, Object> map = new HashMap<>();
    		map.put("last_name", "qaaz");
    		map.put("age", 18);
    		Integer result = empMapper.deleteByMap(map);
    		// DELETE FROM tbl_employee WHERE last_name = ? AND age = ?
    		System.out.println("result="+result);
    	}
    

    条件コンストラクタ(Wrapper)
  • 概要:条件コンストラクタはwrapperという抽象クラスから構成され、このクラスには2つのサブクラスがあり、それぞれEntityWrapperとConditionの2つのクラスであり、2つのサブクラスの用法は同じであり、この例ではEntityWrapperを用いて
  • を紹介する.
  • [外部リンクピクチャの転送失敗(img-GjkVZoIA-156495361812)(assets/1.png)]
  • 条件コンストラクタupdate
    	public void wrapperUpdate() {
    		Employee employee = new Employee();
    		employee.setLastName("kongming");
    		employee.setAge(20);
    		employee.setGender(1);
    		
    		Integer update = empMapper.update(employee, new EntityWrapper<Employee>()
    				.eq("last_name", "efda")
    				.eq("gender", 0)
    				);
    		// UPDATE tbl_employee SET last_name=?, gender=?, age=? WHERE (last_name = ? AND gender = ?)
    		System.out.println("update="+update);
    	}
    

    条件コンストラクタselect
    	public void wrapperSelect() {
    		// 1.          
    		//      qaaz,    18~40  ,     ,     q  
    /*		List list = empMapper.selectList(new EntityWrapper()
    				//          
    				.eq("last_name", "qaaz")
    				.between("age", 18, 40)
    				.or()		// (last_name = ? AND age BETWEEN ? AND ? OR gender = ? AND last_name LIKE ?) 
    				//.orNew()	// (last_name = ? AND age BETWEEN ? AND ?) OR (gender = ? AND last_name LIKE ?)
    				.eq("gender", 1)
    				.like("last_name", "q")
    				);
    		System.out.println(list);
    		*/
    		
    		// 2.         
    //		Integer count = empMapper.selectCount(new EntityWrapper().eq("gender", 1));
    //		System.out.println("count="+count);
    		
    		// 3.         ,          
    //		List list = empMapper.selectObjs(new EntityWrapper().eq("gender", 1));
    //		System.out.println(list);
    		
    		// 4.       ,   
    		//       
    /*		List> list = empMapper.selectMapsPage(new Page(2, 3), new EntityWrapper()
    //				.orderAsc(Arrays.asList(new String[] {"age"} ))		//  
    				.orderDesc(Arrays.asList(new String[] {"age"} ))	//    
    				);
    		// SELECT id,last_name AS lastName,email,gender,age FROM tbl_employee ORDER BY age DESC
    		System.out.println(list);
    		*/
    		
    		// 5.     ,     
    		List<Employee> list = empMapper.selectList(new EntityWrapper<Employee>()
    				.last("limit 1,3"));
    		// .last()    sql      ( sql     ) 
    		// SELECT id,last_name AS lastName,email,gender,age FROM tbl_employee limit 1,3
    		System.out.println(list);
    	}
    

    条件コンストラクタdelete
    public void wrapperDelete() {
    		Integer delete = empMapper.delete(new EntityWrapper<Employee>()
    				.like("last_name", "s")
    				);
    		// DELETE FROM tbl_employee WHERE (last_name LIKE ?)
    		// Parameters: %s%(String)         % 
    		System.out.println("delete = "+delete);
    	}