2

springboot(3)整合mybatis

 2 years ago
source link: https://wakzz.cn/2018/01/22/springboot/(3)%E6%95%B4%E5%90%88mybatis/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1、maven依赖

向pom.xml添加如下依赖

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.github.miemiedev</groupId>
<artifactId>mybatis-paginator</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-juli</artifactId>
<version>8.5.23</version>
</dependency>

2、配置springboot

向application.properties(或者.yml)添加如下配置

#mybaits配置
mybatis.config-location=classpath:mybatis.xml
#等效于mybaits.xml的别名配置
#mybatis.type-aliases-package=com.example.demo.dao.entity
#等效于mybaits.xml的mapper扫描配置
#mybatis.mapper-locations=classpath:com/example/demo/dao/mapper/*.xml

#数据源配置,指定为mysql的c3p0数据源
spring.datasource.name=test
spring.datasource.url=jdbc:mysql://192.168.100.25:6660/TXSMS?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.mchange.v2.c3p0.ComboPooledDataSource

3、Dao层

@Repository
public class TestUserDao {

@Autowired
private SqlSessionTemplate sqlSessionTemplate;

public TXDBUser getUserById(Integer id) {
return sqlSessionTemplate.selectOne("com.wxtx.dao.TestUserDao.selectUserById", id);
}

public List<TXDBUser> getUserList(TXDBUser user, PageBounds pageBounds) {
return sqlSessionTemplate.selectList("com.wxtx.dao.TestUserDao.selectUserList", user, pageBounds);
}

public List<TXDBUser> getPrinterList() {
return sqlSessionTemplate.selectList("com.wxtx.dao.TestUserDao.selectPrinter");
}

public void updateUser(TXDBUser user) {
sqlSessionTemplate.update("com.wxtx.dao.TestUserDao.updateUser", user);
}

}

注:此处的SqlSessionTemplate为springboot自动注册的bean,不需要开发者自己注册实现。

4、事物管理

通过@Transactional注解添加事务,@Transactional注解默认只在发生RuntimeException and Error两种异常时回滚事物。所以实际开发需要指定为当发生任何异常时均回滚事务。

@Service
@Transactional(rollbackFor=Throwable.class) //当发生任何异常时回滚事务
public class TestService {

@Autowired
private TestUserDao userDao;

public List<TXDBUser> getUserList(){
return userDao.getUserList(new TXDBUser(),new PageBounds());
}

}

5、注意事项

所有的xml文件都不能放在src/main/java路径下,否则打包部署的时候会找不到该路径下的所有xml文件。所有非java文件例如mybatis的mapper映射文件均放在src/main/resources路径及子路径下。

这里写图片描述


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK