继上文配置好Spring WebMVC+Spring Framework,继续添加ORM-MyBatis。
pom.xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
添加以上库。
配置步骤如下(java config)
- 封装DataSource, SqlSessionFactoryBean,SqlSession成bean
- 设置MapperScan
- 写Mapper;
- 实现
1,2 封装、MapperScan
MyBatisConfig.java
@Configuration
@MapperScan("jufou.info.mapper")
public class MyBatisConfig {
@Bean
public DataSource dataSource(){
BasicDataSource basicDataSource=new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicDataSource.setUsername("root");
basicDataSource.setPassword("password");
basicDataSource.setUrl("jdbc:mysql://localhost:3306/test");
return basicDataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(){
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:/jufou/info/mybatis/mappers.xml"));
} catch (IOException e) {
e.printStackTrace();
}
return sqlSessionFactoryBean;
}
@Bean
public SqlSession sqlSession(){
SqlSessionTemplate sqlSessionTemplate= null;
try {
sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactoryBean().getObject());
} catch (Exception e) {
e.printStackTrace();
}
finally {
return sqlSessionTemplate;
}
}
}
3,4 Mapper与实现
public interface UserMapper {
@Select("select * from user where uid=#{id}")
public User findById(int id);
}
@Component
@Scope(scopeName="singleton")
public class UserService implements UserServiceImpl {
@Resource(name="sqlSession")
private SqlSession sqlSession;
public UserService(){
}
public String getUserNickname() {
User user=sqlSession.selectOne("jufou.info.mapper.UserMapper.findById", 1);
System.out.println(user.getUid() + "--" + user.getName() + "--");
return "Hello";
}
}
也可以写成xml配置放在mappers.xml内。
至此Java config 版本的SSM配置完成。
网友评论