MyBatis学习之注解式开发

文章目录

  • @Insert
  • @Delete
  • @Update
  • @Select
  • @Results

mybatis中也提供了注解式开发方式,采用注解可以减少Sql语句的维护带来的成本

原则:简单sql可以注解,复杂sql使用xml

@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学习笔记,mybatis,学习)