Mybaits CRUD基于注解的实现
1、定义sql映射的接口
package nh.ui.automation.tools.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import nh.ui.automation.tools.Mybaits.User;
/**
* 项目 :UI自动化测试 Mybaits 类描述:
*
* @author Eric
* @date 2017年3月4日 nh.ui.automation.tools.mapper
*/
public interface UserMapper {
@Insert("insert into user(name,age) values(#{name},#{age})")
public int addUser(User user);
@Delete("delete from user where id = #{id}")
public int deleteUser(int id);
@Update("update user set name=#{name},age=#{age} where id = #{id}")
public int updateUser();
@Select("select * from user where id = #{id}")
public User getUser(int id);
@Select("select * from user")
public List<User> getAllUser();
}
2、Mybaits配置文件注册映射接口
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="Mappings/userMapper.xml"/>
<mapper resource="Mappings/orderMapper.xml"/>
</mappers>
</configuration>
3、测试代码
//其他地方不变,主要通过getMapper方法加载sql映射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUser(2);
System.out.println(user);
int addUser = mapper.addUser(new User("niuh",11));
System.out.println(addUser);
List<User> users = mapper.getAllUser();
System.out.println(users);
int deleteUser = mapper.deleteUser(1);
System.out.println(deleteUser);
List<User> user1s = mapper.getAllUser();
System.out.println(user1s);