Mybatis-使用getMapper()面向借口编程

步骤如下:

1、实体类:

public class Userinfo {

private Long id;

private String username;

private String password;

private Long age;     

//get和set方法

}

2、接口:

public interface UserinfoMapper {

	public void insertUserinfo(Userinfo userinfo);
	
	public List getAllUserinfo();
	
	public Userinfo getUserinfo(long userid);
	
	public void deleteUserinfo(long userid);
	
	public void updateUserinfo(Userinfo userinfo);
	
}
3、SQL映射文件:
  

        
		select idauto.nextval from dual
	

  	insert into userinfo(id,username,password,age)
  	values(#{id},#{username},#{password},#{age})
  
  
  
  	delete from userinfo where id=#{id}
  
  
  	update userinfo set username=#{username},password=#{password},age=#{age}
  	where id=#{id}
  
  



4、mybatis-config.xml配置文件(在src目录下):


	
		
			
			
				
				
				
				
			
		
	
	
		
	


5、测试类:

public static void main(String[] args) {
		
		Userinfo userinfo = new Userinfo();
		userinfo.setUsername("hhh");
		userinfo.setPassword("1456");
		userinfo.setAge(25L);
		SqlSession sqlSession = TestOrm.getSqlSession();
		UserinfoMapper userinfoMapper = sqlSession.getMapper(UserinfoMapper.class);
		userinfoMapper.insertUserinfo(userinfo);
		/*List list = userinfoMapper.getAllUserinfo();
		for(int i=0;i>"+user.getUsername()+">>"+user.getPassword()+">>"+user.getAge());
		}*/
		/*Userinfo user = userinfoMapper.getUserinfo(1);
		System.out.println(user);
		
		user.setPassword("8888");
		userinfoMapper.updateUserinfo(user);*/
		userinfoMapper.deleteUserinfo(2);
		sqlSession.commit();
		sqlSession.close();
		
		System.out.println("createId=" + userinfo.getId());
	}
	
	public static SqlSession getSqlSession(){
		String resource = "mybatis-comfig.xml";
		SqlSession sqlSession = null;
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			sqlSession = sqlSessionFactory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sqlSession;		
	}
}

如果按这样的写完,运行时发现控制台报错:Unknown table 'idauto' in field list

原因是映射文件里面的写法有问题,本来是想将id设置为主键,自动增长的,但是用语句写在MySQL里面不行,最后我解决的办法是:将映射文件开始的语句换成:

    useGeneratedKeys="true" keyProperty="id">
  insert into userinfo(id,username,password,age)
  values(#{id},#{username},#{password},#{age})

 

并且在建表时,设置id为主键并自增。


你可能感兴趣的:(MyBatis)