spring+mybatis整合的三种方式——方式二:采用org.mybatis.spring.SqlSessionTemplate

 2、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。
  mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。SqlSessionFactoryBean有一个必须属性dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
spring-mybatis.xml



    
    
    
    
        
    

    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
    
        
        
        
        
    
    
    
    
        
    

    
    
        
    

sqlMapConfig.xml


  
  
    
        
    

user.java

public class User {
    
    private int id;
    private String username;
    private String password;
    private int age;
     
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

userDao.java

@Repository
public class UserDao{

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;
    
    public User getUser(int id) {
        return sqlSessionTemplate.selectOne(this.getClass().getName() + ".getUser", 1);
    }   
}

userService.java

@Service
public class UserService{
    
    @Resource
    private UserDao userDao;
    
    public User getUser(int id) {
        return userDao.getUser(id);
    }
}

 

你可能感兴趣的:(后端Java,spring,mybatis)