作者:天秤aaaaaaa_150 | 来源:互联网 | 2022-04-27 23:13
和MyBatis类似,Spring或者SpringMVC框架在Web应用程序的运作中同样主要负责处理数据库事务,这里我们就来看一下Java环境中MyBatis与Spring或SpringMVC框架的集成方法
与Spring3集成
Spring作为基础框架,可以集成后端框架,如Hibernate,MyBatis等。
前面是介绍单独使用MyBatis的,大致逻辑是:
sqlSessionFactory <- configuration file (包括数据库连接配置)
IXxxMapper <- sqlSession <- sqlSessionFactory
<- mapper interface <- mapper xml
得到IxxMapper后,就可以调用其方法进行数据交互了。
和Spring集成时,上面的这些对象需要作为bean来管理:
dataSource bean <- 数据库连接配置
sqlSessionFactory bean <- dataSource
<- configuration file
userMapper bean <- sqlSessionFactory
<- mapper interface
1. 在pom.xml中加入依赖:
1.2.1
1.4
3.1.2.RELEASE
org.mybatis
mybatis-spring
${mybatis.spring.version}
org.springframework
spring-jdbc
${spring.version}
commons-dbcp
commons-dbcp
${dbcp.version}
org.springframework
spring-test
${spring.version}
2. 在类路径下创建beans-da.xml文件:
<&#63;xml version="1.0" encoding="UTF-8"&#63;>
3. 测试类:
@ContextConfiguration(locatiOns= { "classpath:beans-da.xml" })
public class SpringIntegrationTest extends AbstractTestNGSpringContextTests {
private static final Logger log = LoggerFactory.getLogger(SpringIntegrationTest.class);
@Resource
IUserMapper mapper;
@Test
public void queryTest() {
User user = mapper.getUserById(1);
log.info("Name: {}, address: {}", user.getName(), user.getAddress());
}
}
与SpringMVC集成
这里我们建立在与Spring3集成基础上来讲:
1. 往pom.xml添加SpringMVC和Freemarker依赖:
2.3.19
2.5
org.freemarker
freemarker
${freemarker.version}
javax.servlet
servlet-api
${servlet.version}
provided
2. 在web.xml中加入Spring的监听器和SpringMVC的servlet:
org.springframework.web.context.ContextLoaderListener
org.springframework.web.context.ContextCleanupListener
hbatis
org.springframework.web.servlet.DispatcherServlet
1
hbatis
*.htm
3. 在WEB-INF下新建:
Spring配置文件applicationContext.xml:
<&#63;xml version="1.0" encoding="UTF-8"&#63;>
类路径下的database.properties:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis&#63;characterEncoding=utf8
user_name=root
password=123456
注:因为MapperScannerConfigurer可能会导致username取的是系统用户的账号,而造成数据库连接失败,所以改成其它值:user_name。
SpringMVC配置文件hbatis-servlet.xml:
<&#63;xml version="1.0" encoding="UTF-8"&#63;>
*.ftl
/WEB-INF/ftl/
4. MVC:
控制层:UserController.java
@Controller
@RequestMapping("/article")
public class UserController {
@Autowired
IUserMapper mapper;
@RequestMapping("/list")
public String showAll(ModelMap modelMap) {
List articles = mapper.getArticlesByUserId(1);
modelMap.addAttribute("articles", articles);
return "main.ftl";
}
}
视图层:main.ftl:
<#list articles as article>
${article.id}. ${article.title}: ${article.content}
#list>
5. 启动工程,浏览器输入:http://localhost:8080/hbatis/article/list.htm查看结果。