mybatis中也提供了注解式开发方式,采用注解可以减少Sql语句的维护带来的成本文章来源:https://www.toymoban.com/news/detail-619272.html
原则:简单sql可以注解,复杂sql使用xml文章来源地址https://www.toymoban.com/news/detail-619272.html
@Insert
// CarMapper.java
@Insert("insert into t_car values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})")
int insert(Car car);
//test文件
@Test
public void test(){
SqlSession sqlSession = SqlSessionUtil.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = new Car(null,null,null,null,null,null,null);
int count = mapper.insert(car);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Delete
@Delete( "delete from t_car where id = #{id}")
int deleteById(Long id);
//test文件
@Test
public void test2(){
SqlSession sqlSession = SqlSessionUtil.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
int count = mapper.deleteById(5L);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Update
@Update("updeate 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文件
@Test
public void test3(){
SqlSession sqlSession = SqlSessionUtil.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
Car car = new Car(6L,null,null,null,null,null,null);
int count = mapper.update(car);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Select
@select( "select * from t_car where id =#{id}")
Car selectById(Long id);
//test文件
@Test
public void test4(){
SqlSession sqlSession = SqlSessionUtil.openSession();
CarMapper mapper = sqlSession.getMapper(CarMapper.class);
int count = mapper.select(5L);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Results
@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);
到了这里,关于MyBatis学习之注解式开发的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!