记:spring整合mybatis-plus 条件构造器(EntityWrapper)

spring整合mybatis-plus的步骤:

  • 和以前spring和mybatis整合很类似,首先将mybatis依赖替换为mybatis-plus的依赖,去掉mybatis-spring依赖,然后把sqlsessionfactory换成mybatis-plus的,然后实体类中添加@TableName、@TableId等注解,最后mapper继承BaseMapper即可。

1.jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://IP :数据库名?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

2.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:p="http://www.springframework.org/schema/p"  
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    
        
    <!-- 配置整合mybatis-plus过程 -->
    <!-- 1、配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!-- 2、配置数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- mybatis的sqlsessionFactorybean:org.mybatis.spring.SqlSessionFactoryBean-->
    <!-- 3、配置mybatis-plus的sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="typeAliasesPackage" value="com.zhu.mybatisplus.entity"/>
    </bean>
    <!-- 4、DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zhu.mybatisplus.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean> 
</beans>

3.sqlMapConfig.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>
注:因为是与spring整合,所有mybatis-plus的大部分都写在spring的配置文件中,这里定义一个空的mybatis-config.xml即可。

4.Entity

@Data
@TableName(value = "tb_employee")//指定表名
public class Employee {
    //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value
    @TableId(value = "id",type = IdType.AUTO)//指定自增策略
    private Integer id;
    //若没有开启驼峰命名,或者表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列
    @TableField(value = "last_name",exist = true)
    private String lastName;
    private String email;
    private Integer gender;
    private Integer age;
}

5.Mapper

public interface EmplopyeeDao extends BaseMapper<Employee> {
}

整合完成。

6.测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class test {
    @Autowired
    private DataSource dataSource;
    @Test
    public void testDataSource() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
}
连接成功。。。。。。。可以进行crud操作了。。。。。。。。。。。

条件构造器(EntityWrapper)

BaseMapper 提供了多达 17 个方法供使用, 可以极其方便的实现单一、批量、分页等操作,极大的减少开发负担。但是mybatis-plus的强大不限于此,请看如下需求该如何处理:
需求:
我们需要分页查询 tb_employee 表中,年龄在 18~50 之间性别为男且姓名为 xx 的所有用户,这时候我们该如何实现上述需求呢?
使用MyBatis : 需要在 SQL 映射文件中编写带条件查询的 SQL,并用PageHelper 插件完成分页. 实现以上一个简单的需求,往往需要我们做很多重复单调的工作。
使用MP: 依旧不用编写 SQL 语句,MP 提供了功能强大的条件构造器 ------ EntityWrapper。

1、分页查询年龄在18 - 50且gender为0、姓名为tom的用户:

List<Employee> employees = emplopyeeDao.selectPage(new Page<Employee>(1,3),
     new EntityWrapper<Employee>()
        .between("age",18,50)
        .eq("gender",0)
        .eq("last_name","tom")
);

注:由此案例可知,分页查询和之前一样,new 一个page对象传入分页信息即可。至于分页条件,new 一个EntityWrapper对象,调用该对象的相关方法即可。between方法三个参数,分别是column、value1、value2,该方法表示column的值要在value1和value2之间;eq是equals的简写,该方法两个参数,column和value,表示column的值和value要相等。注意column是数据表对应的字段,而非实体类属性字段。

2、查询gender为0且名字中带有老师、或者邮箱中带有a的用户:

List<Employee> employees = emplopyeeDao.selectList(
                new EntityWrapper<Employee>()
               .eq("gender",0)
               .like("last_name","老师")
                //.or()//和or new 区别不大
               .orNew()
               .like("email","a")
);

注:未说分页查询,所以用selectList即可,用EntityWrapper的like方法进行模糊查询,like方法就是指column的值包含value值,此处like方法就是查询last_name中包含“老师”字样的记录;“或者”用or或者orNew方法表示,这两个方法区别不大,用哪个都可以,可以通过控制台的sql语句自行感受其区别。
3、查询gender为0,根据age排序,简单分页:

List<Employee> employees = emplopyeeDao.selectList(
                new EntityWrapper<Employee>()
                .eq("gender",0)
                .orderBy("age")//直接orderby 是升序,asc
                .last("desc limit 1,3")//在sql语句后面追加last里面的内容(改为降序,同时分页)
);

注:简单分页是指不用page对象进行分页。orderBy方法就是根据传入的column进行升序排序,若要降序,可以使用orderByDesc方法,也可以如案例中所示用last方法;last方法就是将last方法里面的value值追加到sql语句的后面,在该案例中,最后的sql语句就变为select ······ order by desc limit 1, 3,追加了desc limit 1,3所以可以进行降序排序和分页。
4、分页查询年龄在18 - 50且gender为0、姓名为tom的用户:
条件构造器除了EntityWrapper,还有Condition。用Condition来处理一下这个需求:

 List<Employee> employees = emplopyeeDao.selectPage(
                new Page<Employee>(1,2),
                Condition.create()
                        .between("age",18,50)
                        .eq("gender","0")
 );

注:Condition和EntityWrapper的区别就是,创建条件构造器时,EntityWrapper是new出来的,而Condition是调create方法创建出来。

5、根据条件更新:

@Test
public void testEntityWrapperUpdate(){
        Employee employee = new Employee();
        employee.setLastName("苍老师");
        employee.setEmail("cjk@sina.com");
        employee.setGender(0);
        emplopyeeDao.update(employee,
                new EntityWrapper<Employee>()
                .eq("last_name","tom")
                .eq("age",25)
        );
}

注:该案例表示把last_name为tom,age为25的所有用户的信息更新为employee中设置的信息。
6、根据条件删除:
emplopyeeDao.delete( new EntityWrapper<Employee>() .eq("last_name","tom") .eq("age",16) );

注:该案例表示把last_name为tom、age为16的所有用户删除。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus 中,可以使用实体类的构造器来向数据库插入数据。下面是一个示例: 1. 首先,确保已经引入了 MyBatis-Plus 的依赖包,并且配置好了数据库连接信息。 2. 创建一个实体类,该类对应数据库中的表,并且包含了与表字段对应的属性。 3. 在实体类中,提供一个带有参数的构造器,用于设置插入数据时的字段值。 示例代码如下: ```java import com.baomidou.mybatisplus.annotation.TableName; @TableName("your_table_name") public class YourEntity { private Long id; private String name; // 其他字段... public YourEntity(Long id, String name) { this.id = id; this.name = name; } // 其他字段的 getter 和 setter 方法... } ``` 4. 在需要插入数据的地方,调用 MyBatis-Plus 提供的插入方法,并传入实体对象的构造器参数。 示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @Service public class YourService extends ServiceImpl<YourMapper, YourEntity> { @Autowired private YourMapper yourMapper; public void insertData(Long id, String name) { YourEntity entity = new YourEntity(id, name); yourMapper.insert(entity); } // 其他方法... } ``` 在上述代码中,`YourMapper` 是一个继承了 MyBatis-Plus 提供的 `BaseMapper` 的接口,用于执行数据库操作。 通过调用 `yourMapper.insert(entity)` 方法,可以将实体对象的数据插入到数据库中。 请根据自己的实际情况修改表名、字段名、构造器参数等相关内容,以适应你的项目需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值