MyBatis的Dao层实现方式
首先开发mapper接口:
public interface UserMapper { // 1、 根据用户ID查询用户信息 public User findUserById(int id) throws Exception; // 2、 添加用户 public void insertUser(User user) throws Exception; }
之后创建User的映射文件,在config下创建mapper目录然后创建UserMapper.xml
<mapper namespace="com.itheima.mybatis.mapper.UserMapper"> <!-- 根据用户ID查询用户信息 --> <select id="findUserById" parameterType="int" resultType="User"> SELECT * FROM USER WHERE id =#{id} </select> <!-- 添加用户 --> <insert id="insertUser" parameterType="com.itheima.mybatis.po.User"> <selectKey keyProperty="id" resultType="int" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO USER (username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address}) </insert> </mapper>
之后将映射文件加到全局配置文件即可。然后便可以进行测试:
public class UserMapperTest { private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { // 读取配置文件 // 全局配置文件的路径 String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testFindUserById() throws Exception { // 创建UserMapper对象 SqlSession sqlSession = sqlSessionFactory.openSession(); // 由mybatis通过sqlsession来创建代理对象 UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.findUserById(1); System.out.println(user); sqlSession.close(); } @Test public void testInsertUser() throws Exception { // 创建UserMapper对象 SqlSession sqlSession = sqlSessionFactory.openSession(); // 由mybatis通过sqlsession来创建代理对象 UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(); user.setUsername("东哥hm19"); user.setAddress("宝盛西里24号楼"); mapper.insertUser(user); System.out.println(user.getId()); sqlSession.commit(); sqlSession.close(); } }