标签:
<insert id="insertUser" parameterType="cn.imentors.mybatis.test1.User">
insert into users(name, age) values(#{name}, #{age});
</insert>
<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete>
<update id="updateUser" parameterType="cn.imentors.mybatis.test1.User">
update users set name=#{name},age=#{age} where id=#{id}
</update>
<mappers>
<mapper resource="cn/imentors/mybatis/test1/UserMapper.xml"/>
</mappers>
</configuration>
package cn.imentors.mybatis.util;
public class MybatisUtils {
public static SqlSessionFactory getFactory() {
String resource = "conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
return factory;
}
}
@Test
public void testAdd() {
SqlSessionFactory factory = MybatisUtils.getFactory();
//默认是手动提交的
SqlSession session = factory.openSession();
String statement = "cn.imentors.mybatis.test2.userMapper.insertUser";
int insert = session.insert(statement , new User(3, "KK", 23));
//提交
session.commit();
session.close();
System.out.println(insert);
}
@Test
public void testUpate() {
SqlSessionFactory factory = MybatisUtils.getFactory();
//默认是手动提交的
SqlSession session = factory.openSession(true);
String statement = "cn.imentors.mybatis.test2.userMapper.updateUser";
int update = session.update(statement, new User(3, "KK444", 25));
session.close();
System.out.println(update);
}
@Test
public void testDelete() {
SqlSessionFactory factory = MybatisUtils.getFactory();
// 默认是手动提交的
SqlSession session = factory.openSession(true);
String statement = "cn.imentors.mybatis.test2.userMapper.deleteUser";
int delete = session.delete(statement, 3);
session.close();
System.out.println(delete);
}
public interface UserMapper {
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int insertUser(User user);
@Delete("delete from users where id=#{id}")
public int deleteUserById(int id);
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int updateUser(User user);
@Select("select * from users where id=#{id}")
public User getUserById(int id);
@Select("select * from users")
public List<User> getAllUser();
}
<mapper class="cn.imentors.mybatis.test3.UserMapper"/>
@Test
public void testAdd() {
SqlSessionFactory factory = MybatisUtils.getFactory();
//默认是手动提交的
SqlSession session = factory.openSession(true);
//加载UserMapper接口
UserMapper mapper = session.getMapper(UserMapper.class);
int add = mapper.add(new User(4, "SS", 45));
System.out.println(add);
session.close();
}
标签:
原文地址:http://www.cnblogs.com/mentorStudio/p/4809284.html