第一,要写一个接口,这个接口不需要对应的实现类,在方法上写上对应的增(@Insert),删(@Delete),改(@Update),查(@Select);
第二,配置好Configuration.xml文件;
第三,写一个测试类,读入configuration.xml,创建一个SqlSessionFactory对象,由SqlSessionFactory对象对数据库进行操作。在进行数据库操作之前,一定要注册第一步中的接口,不然系统无法识别我们自己写的接口。
以下是详细的代码:
//PersonMapper 接口 public interface PersonMapper { @Select ( "SELECT * FROM person" ) public List<Person> getAll(); @Select ( "SELECT * FROM person WHERE id = #{id}" ) public Person getPerson( @Param ( "id" ) int id); @Update ( "UPDATE person SET sex=#{sex} WHERE id = #{id}" ) public int updPerson( @Param ( "id" ) int id, @Param ( "sex" ) String sex); @Insert ( "INSERT INTO person(id,age,sex,name,password) VALUES(null,#{age},#{sex},#{name},#{password})" ) public void insertPerson (Person p); @Select ( "DELETE FROM person WHERE id=#{id}" ) public void delPerson( @Param ( "id" ) int id); @Update ( "UPDATE person SET sex=#{sex}, name=#{name},age=#{age}, password=#{password} WHERE id=#{id}" ) public void updatePerson(Person p); } public class PersonImpl{ public static void main(String[] args) { SqlSessionFactory factory = null ; InputStream is = TestIbatis. class .getClassLoader().getResourceAsStream( "Configuration.xml" ); factory = new SqlSessionFactoryBuilder().build(is); //使用注解的时候一定要将XXXMapper注册一下,跟XML配置namespace一样 factory.getConfiguration().addMapper(PersonMapper. class ); //如果不注册Mapper的话,老是报Type interface com.souvi.ibatis.xxxMapper is not known to the MapperRegistry异常 SqlSession sqlSession = factory.openSession(); PersonMapper mp = sqlSession.getMapper(PersonMapper. class ); Person person = new Person(); person.setId( 1 ); person.setName( "杨辉" ); person.setAge( 100 ); mp.updatePerson(person); sqlSession.commit(); } } |