Mybatis学习目录
上一篇:(十四)MyBatis的分页与PageHelper插件
已完结
Mybatis中也提供了注解式开发方式,采⽤注解可以减少Sql映射文件的配置。
当然,使用注解式开发的话,sql语句是写在java程序中的,这种方式也会给sql语句的维护带来成本。
官方是这么说的:
使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂⼀点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做⼀些很复杂的操作,最好用 XML 来映射语句。
原则:简单sql可以注解。复杂sql使用xml。
数据库:汽车表t_car
引⼊依赖:mysql驱动依赖、mybatis依赖、logback依赖、junit依赖。
引入配置文件:jdbc.properties、mybatis-config.xml、logback.xml
SqlSession工具类:SqlSessionUtil
都可以复制之前的
创建CarMapper接口,添加方法:
/**
* 新增数据,使用Insert注解
* @param car
* @return
*/
@Insert("insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})")
int insert(Car car);
测试程序:
@Test
public void testInsert(){
SqlSession session = SqlSessionUtil.getSession();
CarMapper mapper = session.getMapper(CarMapper.class);
int insert = mapper.insert(new Car(null, "6666", "法拉利X", 120.0, "2020-11-10", "燃油车"));
System.out.println(insert);
session.commit();
SqlSessionUtil.close(session);
}
CarMapper接口:
/**
* 根据id删除数据,使用Delete注解
* @param id
* @return
*/
@Delete("delete from t_car where id = #{id}")
int deleteById(Long id);
测试程序:
@Test
public void testDelete(){
SqlSession session = SqlSessionUtil.getSession();
CarMapper mapper = session.getMapper(CarMapper.class);
int deleteById = mapper.deleteById(25L);
System.out.println(deleteById);
session.commit();
SqlSessionUtil.close(session);
}
CarMapper接口:
/**
* 更新语句,使用Update注解
* @param car
* @return
*/
@Update("update t_car set car_num=#{carNum},brand=#{brand},guide_price=#{guidePrice},produce_time=#{produceTime},car_type=#{carType} where id=#{id}")
int update(Car car);
测试程序:
@Test
public void testUpdate(){
SqlSession sqlSession = SqlSessionUtil.getSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = new Car(32L,"6666","丰田霸道",32.0,"2020-11-11","燃油车");
int count = mapper.update(car);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
CarMapper:
@Select("select * from t_car where id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "carNum", column = "car_num"),
@Result(property = "brand", column = "brand"),
@Result(property = "guidePrice", column = "guide_price"),
@Result(property = "produceTime", column = "produce_time"),
@Result(property = "carType", column = "car_type")
})
Car selectById(Long id);
测试程序:
@Test
public void testSelect(){
SqlSession session = SqlSessionUtil.getSession();
CarMapper mapper = session.getMapper(CarMapper.class);
Car car = mapper.selectById(1L);
System.out.println(car);
session.commit();
session.close();
}