方法一:通过配置文件
insert into users(name, age) values(#{name}, #{age}) delete from users where id=#{id} update users set name=#{name}, age=#{age} where id=#{id}
然后在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 ListgetAll();}
然后在conf里配置
使用方式:
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