mybatis CRUD


方法一:通过配置文件

<?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="test2.userMapper">
    <insert id="addUser" parameterType="test.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="test.User">
        update users set name=#{name}, age=#{age} where id=#{id}
    </update>
    
    <select id="getAllUsers" resultType="test.User">
        select * from users
    </select>
</mapper>

然后在conf里配置

使用方式:

String resource = "conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
String statement = "test.userMapper.getUser";
User user = session.selectOne(statement, 2);
System.out.println(user);

 

方式二:注释

package test3;

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 test.User;

public interface UserMapper {
    
    @Insert("insert into users(name, age) values(#{name}, #{age})")
    public int addUser(User user);
    
    @Delete("delete from users where id=#{id}")
    public int deleteById(int id);
    
    @Update("update users set name=#{name}, age=#{age} where id=#{id}")
    public int update(User user);
    
    @Select("select * from users where id=#{id}")
    public User getById(int id);
    
    @Select("select * from users")
    public List<User> getAll();
}

然后在conf里配置

<mappers>
        <mapper resource="test/userMapper.xml"/>
        <mapper resource="test2/userMapper.xml"/>
        <mapper class="test3.UserMapper"/>
</mappers>

使用方式:

String resource = "conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession(true);
UserMapper mapper = session.getMapper(UserMapper.class);
int add = mapper.addUser(new User(-1, "SS", 45));
System.out.println(add);
session.close();        

注意:UserMapper不能和userMapper.xml在同一个包下,例如都是test2然后注册的话会产生冲突,即使一个是userMapper一个是UserMapper

posted on 2015-03-16 22:35  颓废的悠然  阅读(222)  评论(0编辑  收藏  举报

导航