标签:mybatis
User.java实体类
public class User { private int id; private String username; private int age; //... }
userMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mybatis.test02.userMapper"> <!-- CRUD操作 --> <insert id="addUser" parameterType="com.mybatis.test02.User"> insert into users(username, age) values(#{username}, #{age}) </insert> <delete id="deleteUser" parameterType="int"> delete from users where id = #{id} </delete> <update id="updateUser" parameterType="com.mybatis.test02.User"> update users set username = #{username}, age = #{age} where id = #{id} </update> <select id="getUser" parameterType="int" resultType="com.mybatis.test02.User"> select * from users where id=#{id} </select> <select id="getAllUsers" resultType="com.mybatis.test02.User"> select * from users </select> </mapper>
MybatisUtil.java
public class MybatisUtil { public static SqlSessionFactory getFactory() { String resource = "conf.xml"; InputStream inputStream = Test.class.getClassLoader() .getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); return factory; } }
测试方法
@Test public void testAdd() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true);//设置成自动提交 User user2 = new User(); user2.setUsername("ssdd"); user2.setAge(22); String s = "com.mybatis.test02.userMapper.addUser"; int insert = session.insert(s, user2);//受影响记录的条数 //session.commit(); System.out.println(insert); session.close(); } @Test public void testDelete() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true);//设置成自动提交 String s = "com.mybatis.test02.userMapper.deleteUser"; int delete = session.delete(s, 1); //session.commit(); System.out.println(delete); session.close(); } //updateUser @Test public void testUpdate() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); String s = "com.mybatis.test02.userMapper.updateUser"; User user = new User(); user.setId(3); user.setUsername("umgsai"); user.setAge(24); int update = session.update(s, user); System.out.println(update); session.close(); } @Test public void testSelect(){ SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); String s = "com.mybatis.test02.userMapper.getUser"; User user = session.selectOne(s, 5); System.out.println(user); session.close(); } @Test public void testSelectAll() { SqlSessionFactory factory = MybatisUtil.getFactory(); SqlSession session = factory.openSession(true); String s = "com.mybatis.test02.userMapper.getAllUsers"; List<User>users = session.selectList(s); session.close(); System.out.println(users); }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1559082
标签:mybatis
原文地址:http://shamrock.blog.51cto.com/2079212/1559082