MyBatis学习总结(一)mybatis与spring整合
一、需要的jar包
1、spring相关jar包
2、Mybatis相关的jar包
3、Spring+mybatis相关jar包
4、MySql驱动包
5、数据库连接池包
二、配置文件
1、参数文件(db.properties)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
2、spring相关(applicationContext.xml)
< ?xml version="1.0" encoding="UTF-8"?>
< beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--读取配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:SqlMapConfig.xml" /> <!--name必须这么写-->
</bean>
<!--扫描包配置-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mybatis.dao" /> <!--name必须这么写-->
</bean>
</beans>
3、Mybatis相关(SqlMapConfig.xml && Mapper.xml)
3.1 Mybatis核心配置文件
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--起别名-->
<typeAliases>
<package name="com.mybatis.pojo" />
</typeAliases>
</configuration>
< typeAliases>说明:这个在此处是声明pojo的包路径,在mapper.xml文件中,对没个sql的parameterType和resultType可以直接使用pojo的类名,而不用写全路径,而且mapper中的类名和实际pojo的类名可以按照一定的规则不一定要完完全全相同,具体规则此处不赘述
3.2 Mapper映射文件
这只拿查询做一个例子,主要说明mybatis和spring整合的环境搭建
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.mybatis.dao.UserMapper">
<select id="queryById" parameterType="Integer" resultType="user">
select * from user where id = #{id};
</select>
</mapper>
4、测试方法
@Test
public void testMybatis(){
ApplicationContext ca = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMaper = (UserMapper) ca.getBean("userMapper");
User user = userMaper.queryById(1);
System.out.println(user);
}
5、pojo类
package com.mybatis.pojo;
import java.util.Date;
public class User {
private String id;
private String username;
private String sex;
private Date birthday;
private String address;
private String detail;
private Integer score;
get/set...
toString
}