MyBatis学习之注解式开发

文章展示了MyBatis中如何使用注解进行数据库操作,包括@Insert用于插入数据,@Delete删除记录,@Update更新条目,以及@Select查询信息。此外,还提到了@Results注解用于映射查询结果到对象属性。
摘要由CSDN通过智能技术生成

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优降宁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值