什么是AR模式:简单来说就是通过实体类对象,直接进行表的增删改查操作。
实现AR模式在MP中有两个基本要求:
- 实体类继承Model类
//如果不加下面第二个注解,会报一个警告(自动调用equals和hashcode方法,没有调用父类的)
@Data
@EqualsAndHashCode(callSuper = false)
public class User extends Model<User> {
...
}
- 必须存在原始的Mapper接口并继承BaseMapper
public interface UserMapper extends BaseMapper<User> {
...
}
实战演练:
package com.mp.first;
import com.mp.first.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ARTest {
/**
* 这里就不用再注入userMapper了,直接操作实体类就好
*/
@Test
public void insert(){
User user = new User();
user.setName("老刘");
user.setAge(18);
user.setEmail("liu@qq.com");
boolean insert = user.insert();
System.out.println("插入是否成功:"+insert);
}
@Test
public void selectById(){
User user = new User();
User userSelect = user.selectById(1321469479649107970L);
System.out.println("查到了:"+userSelect);
}
@Test
public void selectById2(){
User user = new User();
user.setId(1321469479649107970L);
User userSelect = user.selectById();
System.out.println("查到了:"+userSelect);
}
@Test
public void updateById(){
User user = new User();
user.setId(1321469479649107970L);
user.setName("老王");
boolean userSelect = user.updateById();
System.out.println(userSelect);
}
@Test
public void deleteById(){
User user = new User();
user.setId(1321469479649107970L);
boolean userSelect = user.deleteById();
System.out.println(userSelect);
}
// SELECT id,name,age,email FROM user WHERE id=?
// UPDATE user SET name=?, age=?, email=? WHERE id=?
@Test
public void insertOrUpdate(){
User user = new User();
//不传入id时,是做新增操作
user.setName("老牛");
user.setAge(58);
user.setEmail("laoniu@qq.com");
//传入id时,会先在数据库中找;如果没有此id,怎做新增操作,如果有此id则做修改操作
user.setId(1321473206095212546L);
boolean insert = user.insertOrUpdate();
System.out.println(insert);
}
}