Getting #MybatisPuls basis:

Getting MybatisPuls basis:

Introduction: Using maven build

First, the environment to build --- configuration file (stored in the resources folder)

1).applicationConetext.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
        MP提供的: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>
        <!-- 别名处理  修改地方1 实体类路径-->
        <property name="typeAliasesPackage" value="com.web.pojo"></property>
        
        <!--
           注入全局MP策略配置
           mp 本身存在 globalConfig ,但我们也需要自己引入
        -->
        <property name="globalConfig" ref="globalConfiguration"></property>
    </bean>
    
    <!--
       定义MybatisPlus的全局策略配置
       需要注入到 bean 中才能起作用
    -->
    <bean id ="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
        <!--
          在2.3版本以后,dbColumnUnderline 默认值就是true
            mp 给出了 下划线和驼峰命名 的解决方法
            例如 : 数据库 : list_name  实体类 listName
        -->
        <property name="dbColumnUnderline" value="true"></property>
        
        <!--
            全局的主键策略
            相当于所有的实体类的自增策略是 Type.Auto
        -->
        <property name="idType" value="0"></property>
        
        <!--
             全局的表前缀策略配置 修改地方三  数据库表名前缀
              默认访问的数据库的表示 该前缀 + 实体类名称  = 数据库表名

        -->
        <property name="tablePrefix" value="tbl_"></property>

        
        
    
    </bean>
    
    
    <!-- 
        配置mybatis 扫描mapper接口的路径
     -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 修改地方二 mapper接口 -->
        <property name="basePackage" value="com.web.mapper"></property>
    </bean>
    
</beans>

2)jdbc.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/fenbushi
    jdbc.username=root
    jdbc.password=520

3)log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<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) \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>

4).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>

Second, the need to rely on the environment to build ---

    <dependencies>
    <!-- mp依赖
         mybatisPlus 会自动的维护Mybatis 以及MyBatis-spring相关的依赖
     -->
    <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>

Second, create database tables and entity classes

1.tbl_user table

Note: The configuration file, add the prefix global strategy is to use the benefits of using the MP CRUD entity class can not specify the corresponding operating table

操作的表 = 前缀 + 实体类名 

<property name="tablePrefix" value="tbl_"></property>

2. entity class

 public class User {
    /**
     * TableId
     *    value:表示 主键的列名,如果数据库表中的列名等于实体类的名称可以省略
     *    type:主键自增
     *
     * */
    @TableId(value = "uid",type = IdType.AUTO)
    private Integer uid;
    private String username;
    private String userAge;
    private String usersex;
    private String password;
}

Note: The underlined profile open configuration camelCase turn, so that the entity class userAge name of the database table user_age, (mp-dependent operation if the version is 2.3 or more is automatically turned on by default);

<property name="dbColumnUnderline" value="true"></property>

3. Create and implement an interface mapper BaseMapper <>

BaseMapper provides CRUD most of the object's methods

 public interface UserMapper  extends BaseMapper<User> {}

Third, the operation

1. members disposed in the test class properties

// 读取配置文
private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean容器中的 userMapper接口
private UserMapper userMapper = ioc.getBean("userMapper",UserMapper.class);

2. Check the database connection

 @Test
public void testDataScoure(){
    // 获取配置文件中的datasource
    DataSource ds = ioc.getBean("dataSource",DataSource.class);

    // 查看时否连接上
    System.out.println(ds);

    try {
        // 连接信息
        Connection connection = ds.getConnection();
        System.out.println(connection);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

1. Add: insert

// 添加一个 班级信息
@Test
public void insertClazz(){
    User user = new User();
    user.setUsername("土豆");
    user.setPassword("123");
    user.setUserAge("23");
    Integer insert = usermapperMapper.insert(user);
    System.out.println("影响条数:"+ insert);
    System.out.println("主键id:"+ user.getUid());
}

2. Add: insertAllColumn

   // 添加一个 班级信息
@Test
public void insertClazz(){
    User user = new User();
    user.setUsername("黄瓜");
    user.setPassword("123");
    user.setUserAge("23");
    Integer insert = usermapperMapper.insertAllColumn(user);
    System.out.println("影响条数:"+ insert);
}

A summary:

  • insert: The method of determination comes with non-empty, no attributes property is not added. And if the data is incomplete, can be added to the database but no return value.
  • insertAllColumn: no time to add a non-empty half, all attributes will be added to the database.
  • In addition to query each method returns the number of influence in the database will be added back into the field to add to the database and the values ​​to be added to the class.

3. Modify updateById be modified by id

@Test
public void update(){
    User user =new User();
    user.setUid(1);
    user.setPassword("123");
    user.setUsername("小花");
    Integer update = userMapper.updateById(user);
    System.out.println("影响条数:" + update);
}

The determination method has a non-empty, will modify the properties of the field is not empty

4. Modify the modified overlay updateAllColumnById

  @Test
public void updateColumn(){
    User user =new User();
    user.setId(1);
    user.setPassword("123");
    user.setUsername("土豆");
    Integer update = userMapper.updateAllColumnById(user);
    System.out.println("影响条数:" + update);
}

This method is equivalent to covering, if there is no part of the attribute value, these properties after the implementation of this method will become null databases

The query data by id

 /**
 * 查询方法 selectById
 * */
@Test
public void selectById(){
    User user = userMapper.selectById(1);
    System.out.println("id为1 的记录 :" + user);
}

6. selectOne: query by the entity class non-null property

/**
 * 查询 selectOne
 *
 * */
@Test
public void selectOne(){
    User user1 = new User();
    user1.setUsername("赵小花");
    User user2 = userMapper.selectOne(user1);
    System.out.println("id为1 的记录 :" + user2);
}

Note: If the entity class property is not empty, the default will be a condition for the query
pit: If the query when certain properties are all much the same, when the query error. Because the method can only return of data

7. selectBatchIds: query the data set id (parameter set type)

 /**
 * 查询 selectBatchIds
 *
 *    通过id 集合查询数据
 * */
@Test
public void selectByIds(){
    List<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    ids.add(2);
    List<User> users = userMapper.selectBatchIds(ids);
    System.out.println("id为1 的记录 :" + users);
}

8. selectByMap: map a set of query data encapsulated data (parameter map set)

/**
 *map集合封装的数据查询数据(参数为map集合)  
 *    
 * */
@Test
public void selectMap(){
   Map<String,Object> map = new HashMap<String,Object>();
   map.put("username","赵小花");
   map.put("user_age","25");
   map.put("password","123");
   List<User> users = userMapper.selectByMap(map);

    System.out.println("查询结果:" + users);
}

NOTE: map database tables corresponding to the primary key field, is not a property of the entity class

Wrapper classes have achieved EntityMapper and Condition

9.selectList Conditions builder query data

/**
 * 条件构造器 条件查询
 *
 *  降序查询数据
 *
 * */
@Test
public void selectByWrapper1(){

    List<User> users = userMapper.selectList(
            new EntityWrapper<User>().eq("password", "123")
                                     // 两者存起一就好好 推荐使用第一个
                                     // .orderDesc(Arrays.asList(new String[] {"user_age"})) // orderDesc 和 orderAsc 的参数都是 集合可以借助Arrays完成数据操作
                                      .orderBy("user_age") // 默认的是升序 不是降序 可以使用 last 注入自定义的sql 语句
                                      .last("desc limit 1,3")// last 表示 在sql后面拼接sql语句 这样就无法防止sql注入
    );

    System.out.println(users);
}

10.selectList: Condition condition construction

/**
 * 条件构造器 条件查询
 *
 *  降序查询数据
 *
 * */
@Test
public void selectByWrapper1(){

    List<User> users = userMapper.selectList(
            Condition.create().eq("password", "123")
                                     // 两者存起一就好好 推荐使用第一个
                                     // .orderDesc(Arrays.asList(new String[] {"user_age"})) // orderDesc 和 orderAsc 的参数都是 集合可以借助Arrays完成数据操作
                                      .orderBy("user_age") // 默认的是升序 不是降序 可以使用 last 注入自定义的sql 语句
                                      .last("desc limit 1,3")// last 表示 在sql后面拼接sql语句 这样就无法防止sql注入
    );

    System.out.println(users);
}

Summary: The difference is that the Condition and EntityWarpper

  • Condition is () method created by create out
  • EntityWarpper need new out

11.selectPage: + paging query condition

/**
 * 条件构造器 分页条件查询
 *
 *  需求 性别为男  姓名为 xxx的用户  年龄在 11   到 25之间的用户信息
 *  每页显示 2条数据
 *
 * */
@Test
public void selectByWrapper2(){
    List<User> users = userMapper.selectPage(new Page<User>(1, 2),
            new EntityWrapper<User>().between("user_age", "11","25")
                    .eq("usersex", "男")
                    .eq("username", "张三"));

    System.out.println(users);
}

12.update: Condition memory modify builder

    /**
     * 条件构造器 条件查询
     * 修改密码为 123,姓名为张三 或 姓名包含五的人的密码为6666
     * 
     * */
    @Test
    public void updateWrapper(){
        User user =  new User();
        user.setPassword("6666");

        Integer update = userMapper.update(user, new EntityWrapper<User>().eq("password", "123")
                .eq("username", "张三")
                .or() // 后面又是 条件组合
                .like("username", "五"));

        System.out.println("影响条数:" + update);
    }

13.update: Condition memory modify builder

    /**
     * 条件构造器 条件查询
     * (修改密码为 123,姓名为张三 )或 (姓名包含五密码为111得人),人的密码为6666
     * 
     * */
    @Test
    public void updateWrapper(){
        User user =  new User();
        user.setPassword("6666");

        Integer update = userMapper.update(user, new EntityWrapper<User>().eq("password", "123")
                .eq("username", "张三")
                .orNew() // 后面又是 条件组合
                .like("username", "五")
                .eq("username","111"));
        System.out.println("影响条数:" + update);
    }

summary:

  • or () is represented by the foregoing conditions and the same level that the relationship
  • orNew () indicates the rear of the latter is another condition (condition combination)

14.deleteById: delete the message by id

/**
     * 删除 deleteById(Id)
     *
     * */
    @Test
    public void deleteById(){
        Integer integer = userMapper.deleteById(1);
        System.out.println("影响条数:" + integer);
    }   

15. deleteBatchIds: (a query similar) by deleting the collection of data id

 /**
 * 删除 deleteBatchIds(List supper)
 *   ids 的集合
 * */
@Test
public void deleteBatchIds(){
   List<Integer> list = new ArrayList<Integer>();
   list.add(2);
   list.add(4);
   Integer integer = userMapper.deleteBatchIds(list);
   System.out.println("影响条数:" + integer);
}

16.deleteMap delete (and selectMap use similar)

/**
 * 删除 deleteByMap(Map supper)
 *   map中的主键仍然是数据库表的字段
 * */
@Test
public void deleteByMap(){
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("usernmame","张三");
    map.put("password","123");
    Integer integer = userMapper.deleteByMap(map);
    System.out.println("影响条数:" + integer);
}

17.delete: Conditions construction delete

/**
 * 条件构造器 条件删除
 *删除年龄等于 23 或姓名包含五的数据
 *
 * */
@Test
public void deleteWrapper(){
    Integer delete = userMapper.delete( new EntityWrapper<User>().eq("password", "123")
            .eq("user_age", "23")
            .orNew() // 后面又是 条件组合
            .like("username", "五"));

    System.out.println("影响条数:" + delete);
}

Guess you like

Origin www.cnblogs.com/yizhichenfen/p/11914066.html