<properties>
<mybatisplus.version>3.2.0mybatisplus.version>
<spring.version>4.3.9.RELEASEspring.version>
<mysql.version>5.1.39mysql.version>
<log4j.version>1.2.17log4j.version>
<lombok.version>1.18.10lombok.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-expressionartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plusartifactId>
<version>${mybatisplus.version}version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
<optional>trueoptional>
dependency>
dependencies>
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName(value = "dept")//与数据库表映射
public class Dept implements Serializable {
@TableId(value="pid")//表示主键,带参数表示将属性和表字段映射,若属性和字段名一致可以不加
private Integer id;
private String pname;
@TableField(value = "premark")//若属性名和表字段名一致可以不加
private String premark;
}
public interface DeptMapper extends BaseMapper<Dept> {
}
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
作用:mp只能操作单表,要是多表,则可以在 mapper.xml中拓展
<mapper namespace="com.sxt.mapper.UserMapper">
mapper>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">
<context:component-scan base-package="com.itan.service"/>
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
bean>
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="globalConfig" ref="globalConfig"/>
<property name="mapperLocations">
<array>
<value>classpath:mapper/*Mapper.xmlvalue>
array>
property>
<property name="plugins">
<array>
<bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">bean>
array>
property>
bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig" ref="dbConfig">property>
bean>
<bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
<property name="idType" value="AUTO"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itan.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
bean>
beans>
主方法
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
DeptMapper deptMapper=context.getBean(DeptMapper.class);
//addDept(deptMapper);
//uppDept(deptMapper);
//delDept(deptMapper);
//queryDept(deptMapper,"销售");
}
添加
public static void addDept(DeptMapper deptMapper){
deptMapper.insert(new Dept(null, "人事部", "123456"));
}
删除
public static void delDept(DeptMapper deptMapper){
//1、根据主键删除,相当于DELETE FROM dept WHERE pid=?
deptMapper.deleteById(126);
//2、批量删除,相当于使用DELETE FROM dept WHERE pid IN ( ? , ? )
Collection<Serializable> idList = new ArrayList<Serializable>();
idList.add(135);
idList.add(136);
deptMapper.deleteBatchIds(idList);
//3、多条件删除,相当于DELETE FROM dept WHERE pname = ? AND pid = ?
Map<String,Object> map=new HashMap<>();
map.put("pid",131);
map.put("pname","人事部");
deptMapper.deleteByMap(map);
//4、查询删除,先查询出来再删除
Wrapper<Dept> wrapper=new QueryWrapper<>();
((QueryWrapper<Dept>) wrapper).between("pid",131,132);
deptMapper.delete(wrapper);
}
修改
public static void uppDept(DeptMapper deptMapper){
//1、根据主键修改
deptMapper.updateById(new Dept(125, "人事部", "小美女多"));
//2、多条件修改:eq(表的字段,要修改的值)
//相当于:UPDATE dept SET premark=?, pname=? WHERE (pname = ? AND premark = ?)
UpdateWrapper<Dept> updateWrapper=new UpdateWrapper<>();
updateWrapper.eq("pname","销售");
updateWrapper.eq("premark","销售多");
//3、between(表的字段,条件1,条件2):修改在条件1到条件2之间的数据
//相当于:UPDATE dept SET premark=?, pname=? WHERE (id BETWEEN ? AND ?)
updateWrapper.between("pid",125,128);
deptMapper.update(new Dept(null, "销售", "销售人才多"),updateWrapper);
}
查询(注:使用分页查询要配置分页插件)
public static void queryDept(DeptMapper deptMapper,String pname){
//1、根据主键id查询
Dept dept = deptMapper.selectById(130);
System.out.println(dept);
//2、根据主键id使用in关键字的sql查询
Collection<Serializable> idList = new ArrayList<Serializable>();
idList.add(133);
idList.add(134);
List<Dept> depts = deptMapper.selectBatchIds(idList);
//3、多条件使用and关键字的sql查询
Map<String,Object> map=new HashMap<>();
map.put("pid",129);
map.put("premark","456");
List<Dept> depts = deptMapper.selectByMap(map);
//4、查询所有条数
Integer integer = deptMapper.selectCount(null);
//5、带条件的查询
Wrapper<Dept> wrapper=new QueryWrapper<>();
((QueryWrapper<Dept>) wrapper).like(pname!=null,"pname",pname);
Integer integer = deptMapper.selectCount(wrapper);
//6、不带条件的分页
IPage<Dept> page = new Page<>(1,5);
deptMapper.selectPage(page,null);
long total = page.getTotal();//总条数
System.out.println("总条数:"+total);
List<Dept> depts = page.getRecords();//所有的数据
for(Dept d:depts){
System.out.println(d);
}
}
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.2.0version>
dependency>
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName(value = "dept")//与数据库表映射
public class Dept implements Serializable {
@TableId(value="pid")//表示主键
private Integer id;
private String pname;
@TableField(value = "premark")//若属性名和表字段名一致可以不加
private String premark;
}
注:要加@Mapper
注解或者在启动类上加@MapperScan(basePackage={"com.itan.mapper"})
@Mapper
public interface DeptMapper extends BaseMapper<Dept> {
}
#配置数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useSSL=true&serverTimezone=UTC
username: root
password: 123456
#指明数据源用哪个
type: org.springframework.jdbc.datasource.DriverManagerDataSource
#配置mybatisplus
mybatis-plus:
#扫描mapper文件
mapper-locations:
- classpath:mapper/*Mapper.xml
#配置主键自增
global-config:
db-config:
id-type: auto
banner: true
#打印sql语句
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@Configuration
@ConditionalOnClass(value = {PaginationInterceptor.class})
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor myBatisPlus(){
return new PaginationInterceptor();
}
}
@Test
void pageDept(){
IPage<Dept> page = new Page<>(1, 5);
deptMapper.selectPage(page,null);
List<Dept> lis = page.getRecords();
for (Dept d:lis){
System.out.println(d);
}
System.out.println("总数:"+page.getTotal());
}
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName(value = "dept")//与数据库表映射
public class Dept extends Model<Dept> implements Serializable {
@TableId(value="pid")//表示主键
private Integer id;
private String pname;
@TableField(value = "premark")//若属性名和表字段名一致可以不加
private String premark;
@TableField(exist = false)//当查询结果中没有这个字段可以用这个方法忽略掉这个属性
private String sex;
}
@Test
void addDept(){
Dept dept=new Dept();
dept.setId(null);
dept.setPname("后勤部");
dept.setPremark("456");
boolean b = dept.insert();
System.out.println(b);
}
@Test
void pageDept(){
Dept dept=new Dept();
IPage<Dept> page=new Page<>(1,5);
dept.selectPage(page,null);
long total = page.getTotal();
System.out.println("总数:"+total);
}
@Test
void wrapperTest(){
QueryWrapper<Dept> wrapper = new QueryWrapper<>();
//or关系,不加or默认是and关系
wrapper.eq(true,"id",1).or().eq("id",2);
//and关系
wrapper.between(true,"id",127,130);
//小于关系
wrapper.lt("id",128);
//小于等于关系
wrapper.le("id","128");
//大于关系
wrapper.gt("id",128);
//大于等于关系
wrapper.ge("id",128);
//排序
wrapper.orderByAsc("id");
System.out.println(wrapper.getSqlSegment());
}
<dependencies>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.1version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.29version>
dependency>
<dependency>
<groupId>com.ibeetlgroupId>
<artifactId>beetlartifactId>
<version>3.0.16.RELEASEversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.17version>
dependency>
dependencies>
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;
/**
*MP代码生成器
*/
public class Codegenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("itan");
//当代码生成后是否打开代码所在的文件夹
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
//给service设置名字
gc.setServiceName("%sService");
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/ssm?useSSL=true&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
//设置父模块名
pc.setParent("com.itan");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//设置字段和表名是否把下划线改成驼峰命名规则
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//是否启用lombokl
strategy.setEntityLombokModel(true);
//是否生成RestController
strategy.setRestControllerStyle(true);
// 设置生成的控制器类继承的父类
// strategy.setSuperControllerClass("com.itan");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
//要设置生成哪些表,如果不设置就是生成所有的表
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
示例:
@RequestMapping("getAll")
public DataGridView getAll(CustomerVo customerVo){
//分页插件
IPage<Customer> page = new Page<>(customerVo.getPage(),customerVo.getLimit());
//条件构造
QueryWrapper<Customer> wrapper=new QueryWrapper<>();
wrapper.like(StringUtils.isNotBlank(customerVo.getCustomername()),"customername",customerVo.getCustomername());
wrapper.like(StringUtils.isNotBlank(customerVo.getTelephone()),"telephone",customerVo.getTelephone());
wrapper.like(StringUtils.isNotBlank(customerVo.getConnectionperson()),"connectionperson",customerVo.getConnectionperson());
//执行
this.customerService.page(page,wrapper);
return new DataGridView(page.getTotal(),page.getRecords());
}