MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
<!-- 引入数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- springBoot数据库连接 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- spring整合mybatis 暂时 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <!-- spring整合mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency>
@SpringBootApplication @MapperScan("com.jt.mapper") public class SpringBootRun { public static void main(String[] args) { SpringApplication.run(SpringBootRun.class); } }
public interface CarMapper extends BaseMapper<Car> { List<Car> findAll(); @Insert("insert into car(id,name,color,price) value (null,#{name},#{color},#{price})") void insertCar(Car car); @Update("update car set name=#{newName} where name=#{oldName}") void updateByName(String oldName,String newName); @Delete("delete from car where name=#{name}") void deleteByName(String name); }
@Data @Accessors(chain = true) @TableName("car") public class Car { @TableId(type = IdType.AUTO) private Integer id; private String name; private String color; private Double price; }
<mapper namespace="com.jt.mapper.CarMapper"> <sql id="rols"> id,name,color,price </sql> <select id="findAll" resultType="Car"> select * from car </select> </mapper>
@SpringBootTest(classes = SpringBootRun.class) public class TestMybatis { @Autowired private CarMapper carMapper; @Test public void testInster(){ System.out.println(carMapper.getClass()); List<Car> carList; carList=carMapper.findAll(); System.out.println(carList); } @Test public void testfind(){ List<Car> carList=carMapper.selectList(null); System.out.println(carList); } @Test public void insert(){ Car car=new Car(); car.setId(4).setName("卡宴").setColor("黄色").setPrice(1888.8); carMapper.insert(car); System.out.println("新用户增加成功"); } @Test public void update(){ String oldName="卡宴"; String newName="保时捷卡宴"; carMapper.updateByName(oldName,newName); System.out.println("用户修改成功"); } @Test public void delete(){ String name="宝马X5"; carMapper.deleteByName(name); System.out.println("用户删除成功"); } }