创建实体类省略【get方法,set方法,构造方法】
<!--简化bean代码的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.4</version>
</dependency>
实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
mp整合mybatis
- UserMapper.java接口继承BaseMapper<T>:就可以使用BaseMapper<T>中的方法
public interface UserMapper extends BaseMapper<User> { List<User> findAll(); }
- 实体类用的哪个表
@TableName("tb_user")
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
- 使用mp提供的MybatisSqlSessionFactoryBuilder构建工厂创建SqlSessionFactory,此时就可以使用BaseMapper中的方法
public class TestMybatis {
@Test
public void testFindAll(){
try {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new MybatisSqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//List<User> all = mapper.findAll();
List<User> all = mapper.selectList(null);
for (User user:all) {
System.out.println(user);
}
sqlSession.commit();
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
mp,mybatis,spring整合
pom
<properties>
<spring.version>5.1.6.RELEASE</spring.version>
</properties>
<!--spring相关-->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
applicationContext
<context:property-placeholder location="classpath:*.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml"/><!--可以不写 mybatis核心文件-->
</bean>
<!--扫描mapper所在的包 为mapper创建实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xjbt.mapper"></property>
</bean>
test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestMybatis {
@Autowired
private UserMapper userMapper;
@Test
public void testFindAll() {
List<User> all = userMapper.selectList(null);
for (User user : all) {
System.out.println(user);
}
}
}
springboot mybatis mp整合
pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--简化代码的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.20</version>
</dependency>
<!--mybatis-plus的springboot支持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
MyApplication主文件
@MapperScan("com.xjbt.mapper")
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
application.properties
spring.application.name = springbootmybatis_plusmybatis
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
测试
mp 通用crud操作
实体类注解
@Data //get set toStrong...
@NoArgsConstructor //无参构造
@AllArgsConstructor //有参构造
//下边都是mybatis-plus注解
@TableName("tb_user") //使用那张数据表
public class User {
@TableId(type = IdType.AUTO) //自增
private Long id;
//1,字段名称和属性名不一致使用
@TableField("user_name")
private String user;
//2,属性在数据库中不存在
@TableField(exist = false)
private String addr;
//3,字段不加入查询字段
@TableField(select = false)
private String password;
private String name;
private Integer age;
private String email;
}
1. 插入操作:
int insert(T entity); 返回发生变化的记录行数
@Test
public void testInsert() {
User user=new User();
user.setUserName("dd");
user.setPassword("123");
userMapper.insert(user);
System.out.println(user);
System.out.println("id=>"+user.getId());//自增后的id会回填到对象中
}
设置id生成策略:@IdType
@Getter
public enum IdType {
AUTO(0) =>数据库id自增长
NONE(1) =>该类型为未设置主键类型
INPUT(2) =>用户输入ID
========以下3种类型、只有当插入对象ID 为空,才自动填充。 =========
ID_WORKER(3),=>全局唯一ID[idWorker]
UUID(4) =>全局唯一ID[UUID]
ID_WORKER_STR(5) =>字符串全局唯一ID (idWorker 的字符串表示)
2. 更新操作:
- 根据id:
int updateById(@Param(Constants.ENTITY) T entity)
@Test public void testUpdate(){ User user=new User(); user.setId(8L); user.setAge(12); userMapper.updateById(user); }
- 根据条件更新:
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/** * QueryWrapper */ @Test public void testUpdate(){ //UPDATE tb_user SET age=? WHERE age=? AND user_name = ? User user=new User(); user.setAge(21);//set更新 QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(user); userQueryWrapper.eq("user_name","张三");//where条件 userMapper.update(user,userQueryWrapper); } /** * UpdateWrapper */ @Test public void testUpdate2(){ //UPDATE tb_user SET age=?,user_name=? WHERE user_name = ? User user=new User(); UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>(user); userUpdateWrapper.set("age",22).set("user_name","admin"); userUpdateWrapper.eq("user_name","zhangsan"); userMapper.update(null,userUpdateWrapper); }
3. 删除操作:
- 根据id:
int deleteById(Serializable id);
@Test public void testDeleteById() { int result = this.userMapper.deleteById(6L); }
- 多条件查询:
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
@Test public void testDeleteMap(){ Map<String,Object> hashMap=new HashMap<String,Object>(); hashMap.put("User_name","dd"); hashMap.put("age",null); userMapper.deleteByMap(hashMap); }
- 根据实体类对象:
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
@Test public void testDeleteByEnty() { User user=new User(); //1[推荐]面向对象 不用写字段 user.setUser("dd"); user.setAge(12); QueryWrapper<User> userQueryWrapper =new QueryWrapper<User>(user); userMapper.delete(userQueryWrapper); //2 /* QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.eq("user_name","dd").eq("age",null); userMapper.delete(userQueryWrapper);*/ }
4.批量删除:int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
@Test
public void testDeleteBatchIds() {
userMapper.deleteBatchIds(Arrays.asList(9,10));
}
5. 查询:
- 通过id查询:
T selectById(Serializable id);
@Test public void testSelectById() { User user = userMapper.selectById(1); System.out.println(user); }
- 根据id批量查询:
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
@Test public void testSelectBatchIds() { List<User> userList = userMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4, 5)); System.out.println(userList); }
- 根据条件查询一条数据:
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@Test public void testSelectOne() { QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.eq("user_name","admin"); User user = userMapper.selectOne(userQueryWrapper); }
- 根据 Wrapper 条件,查询总记录数:
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@Test public void testSelectCount() { QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.gt("age","20"); int userCount = userMapper.selectCount(userQueryWrapper); System.out.println(userCount); }
- 根据 entity 条件,查询全部记录:
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
@Test public void testSelectList() { QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.like("email","it"); List list = userMapper.selectList(queryWrapper); System.out.println(list); }
- 分页查询:
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
配置类
分页测试@Configuration @MapperScan("com.xjbt.mapper") public class MyBatisplusPage { @Bean //配置分页插件 public PaginationInterceptor paginationInterceptor(){//拦截器 return new PaginationInterceptor(); }
//分页测试 @Test public void testIpage(){ Page<User> page = new Page<User>(1,1); QueryWrapper queryWrapper=new QueryWrapper(); queryWrapper.like("email","it"); IPage iPage = userMapper.selectPage(page, queryWrapper); System.out.println("总条数"+iPage.getTotal()); System.out.println("总页数"+iPage.getPages()); System.out.println("当前页"+iPage.getCurrent()); List<User> records = iPage.getRecords(); for (User user:records) { System.out.println(user); } }
mybatis-plus基本配置
-
springbooot【配置文件application.prooerties】
mybatis-plus.configuration和mybatis-plus.config-location不能同时存在
- 指定全局的配置文件
mybatis-plus.config-location=classpath:mybatis-config.xml
- 指定mapper【可以写自己定义的方法】
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
- 实体对象的扫描包 给实体类起别名
mybatis-plus.type-aliases-package=com.xjbt.pojo
- 禁用自动驼峰映射【字段user_name可写成userName】
全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true。不能和第一项一起使用,第一项的意思是使用mybatis核心配置文件,mybatis默认禁用驼峰命名和这个禁用起冲突 mybatis-plus.configuration.map-underscore-to-camel-case=false
全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。mybatis-plus.configuration.cache-enabled=false
表名前缀,全局配置后可省略@TableName()配置。mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.table-prefix=tb_
- 指定全局的配置文件
-
ssm【配置文件applicationContext.xml】
- 指定全局的配置文件
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> =>指定全局的配置文件dataSource <property name="dataSource" ref="dataSource" /> =>指定全局的配置文件 <property name="configLocation" value="classpath:mybatis-config.xml"/> =>指定mapper 可以定义方法 <property name="mapperLocations" value="classpath:UserMapper.xml"/> =>给实体类起别名 <property name="typeAliasesPackage" value="com.xjbt.pojo"/> <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig"> <property name="dbConfig"> --=> 全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。--> <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig"> <property name="idType" value="AUTO"/> => 表名前缀,全局配置后可省略@TableName()配置。--> <property name="tablePrefix" value="tb_"/> </bean> </property> </bean> </bean>
- 指定全局的配置文件
条件构造器【可去官网:https://baomidou.com/pages/10c804/#having有完整的示例】
allEq:
@Test
public void testSelectAllEq() {
Map<String,Object> map=new HashMap<>();
map.put("name","张三");
map.put("age",22);
map.put("password","123456");
QueryWrapper<User> queryWrapper=new QueryWrapper<>();
// SELECT id,user_name AS user,name,age,email FROM tb_user WHERE password = ? AND name = ? AND age = ?
queryWrapper.allEq(map);
// SELECT id,user_name AS user,name,age,email FROM tb_user WHERE password = ? AND name = ?
queryWrapper.allEq(map,false)忽略条件中vlaue是null的
查询key中包含"g"的key
// SELECT id,user_name AS user,name,age,email FROM tb_user WHERE age = ?
queryWrapper.allEq((k,v) -> k.contains("g"),map);
userMapper.selectList(queryWrapper);
}
ActiveRecord【AR】
定义:
ActiveRecord也属于ORM(对象关系映射)层,由Rails最早提出。
遵循标准的ORM模型:表映射到记录【一行数据】,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很大程度的快速实现模型的操作,而且简洁易懂。
ActiveRecord的主要思想是:
- 表对应类,类中的属性对应了表中的字段,类的实例化对应表中的数据
- ActiveRecord同时负责把自己持久化,在ActiveRecord中封装了对数据库的访问,即CURD;
- ActiveRecord是一种领域模型(Domain Model),封装了部分业务逻辑;
使用AR
实体类继承Model<T>
public class User extends Model<User>
测试:
@Test
public void testAR(){
User user = new User();
user.setId(2L);
User user2 = user.selectById();
System.out.println(user2);
}
方法和mybatis方法一样。
mybatis插件机制:
MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法
调用包括:
1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)【1. 拦截执行器的方法】
2. ParameterHandler (getParameterObject, setParameters)【2. 拦截参数的处理】
3. ResultSetHandler (handleResultSets, handleOutputParameters)【3. 拦截结果集的处理】
4. StatementHandler (prepare, parameterize, batch, update, query)【4. 拦截Sql语法构建的处理】