第一种:
配置sqlMapConfig.xml(mybatis核心配置文件)
<!-- 配置数据源,事务 -->
<environment id="test">
<!-- 事务:JDBC/MANAGED-自己管理去 -->
<transactionManager type="JDBC"/>
<!-- 数据源:POOLED/UNPOOLED/JNDI -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?charsetEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
<!-- 映射文件mapper -->
<mappers>
<mapper resource="cn/itcast/mapper/PersonMapper.xml"/>
</mappers>
创建mapper.xml
<!-- 自定义命名空间-->
<mapper namespace="cn.itcast.mapper.PersonMapper">
<!-- 查询一个,按id查询 -->
<select id="get" parameterType="int" resultType="cn.itcast.domain.Person">
select * from person
where id = #{pid}
</select>
</mapper>
在测试类中使用:
private SqlSessionFactory factory;
@Before //最先执行,初始化SessionFactory
public void init() throws IOException{
String resource = "sqlMapConfig.xml";
InputStream is = Resources.getResourceAsStream(resource);
factory = new SqlSessionFactoryBuilder().build(is);
}
@Test //查询一条
public void testGet(){
SqlSession session = factory.openSession();
Person p = session.selectOne("cn.itcast.mapper.PersonMapper.get", 1);
//cn.itcast.mapper.PersonMapper:mapper.xml中定义的命名空间
// get:各种操作定义的id
System.out.println(p);
}
后面是三种都是结合spring,且动态生成mapper代理。
程序员只需要编写mapper接口(相当于dao接口),不需要编写 mapper接口的实现类,mybatis提供根据mapper接口和mapper.xml(映射文件)生成mapper接口动态代理对象(mapper接口的实现)。
具备什么规则生成mapper代理对象:
Mapper.xml中的namespace等于mapper接口的地址。
Mapper.xml中定义的sql的id(mapped statement的id)等于mapper.java中方法名
Mapper.xml中定义的statement的parametertype等于mapper.java中方法的形参类型。
Mapper.xml中定义的statement的resultType等于mapper.java中方法的返回值类型。
第二种 :
sqlMapConfig.xml核心配置文件不需要再配置xxxmapper.xml
applicationContext.xml:spring核心配置文件
<!-- 1.jdbc.properties属性配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 2.数据源 DataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverclass}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 3.SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- spring和mybatis整合 -->
<!-- 1)引入mybatis核心配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
<!-- 2)扫描指定目录下的所有Mapper.xml -->
<property name="mapperLocations" value="classpath:cn/itcast/ssm/mapper/*.xml"/>
</bean>
创建mapper.xml:personMapper.xml
<!-- 自定义命名空间-->
<mapper namespace="cn.itcast.mapper.PersonMapper">
<!-- 带条件查询 -->
<select id="find" parameterType="map" resultMap="personRM">
select * from person
where 1=1
<if test="name!=null"> and user_name like #{name}</if>
<if test="ageStart!=null"> and age>#{ageStart}</if>
<if test="ageEnd!=null"><![CDATA[ and age<=#{ageEnd}]]></if>
</select>
<!-- 查询某人的书籍 -->
<select id="findPersonBook" parameterType="int" resultMap="personBookRM">
SELECT
p.id,p.user_name,p.age,p.remark,
b.id AS book_id,b.name,b.money
FROM
(SELECT * FROM person
WHERE id = #{id}
) p
LEFT JOIN
(SELECT * FROM book
WHERE person_id = #{id}
) b
ON p.id=b.person_id
</select>
<!-- 新增 -->
<insert id="insert" parameterType="cn.itcast.ssm.domain.Person">
insert into person
(user_name,age,remark)
values
(
#{name, jdbcType=VARCHAR},
#{age, jdbcType=INTEGER},
#{remark, jdbcType=VARCHAR}
)
</insert>
</mapper>
创建PersonMapper接口文件,接口文件路径一定要和xxxmapper.xml文件namespace名称一致。
public interface PersonMapper {
public List<Person> find(Map map);
public void insert(Person person);
public Person findPersonBook(Integer id);
// 需要注意的是方法中的参数要和mapper.xml中定义的参数类型一致
}
编写dao层
@Repository
public class PersonDaoImpl extends SqlSessionDaoSupport implements PersonDao {
/*
* mybatis3.0.0+mybatis-psring1.0.0无需,整合包自己注入
* mybatis3.2.2+mybatis-spring1.2.0 必须自己注入sqlSessionFactory;
*/
@Resource
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
public List<Person> find(Map map){
PersonMapper mapper = this.getSqlSession().getMapper(PersonMapper.class);
return mapper.find(map);
}
public void insert(Person person){
PersonMapper mapper = this.getSqlSession().getMapper(PersonMapper.class);
mapper.insert(person);
}
public Person findPersonBook(Integer id){
PersonMapper mapper = this.getSqlSession().getMapper(PersonMapper.class);
return mapper.findPersonBook(id);
}
}
第三种 :
sqlMapConfig.xml核心配置文件不需要再配置xxxmapper.xml
注意:mapper.xml和mapper.java同名且在一个目录 ,不需要在SqlMapConfig.xml中加载mapper文件。
applicationContext.xml:spring核心配置文件
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<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="${jdbc.maxActive}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置SqlSessionFactory
从spring和mybatis的整合包中获取
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置SqlMapConfig.xml -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
</bean>
<!-- 使用MapperFactoryBean 生成mapper的代理对象
在mybatis和spring的整合包中
-->
<bean id="sysuserCustomMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
配置mapper接口
<property name="mapperInterface" value="yycg.base.dao.mapper.SysuserCustomMapper"/>
配置sqlSessionFactory
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
编写xxxmapper.xml文件
<!-- 带条件查询 -->
<select id="findSysuserById" parameterType="int" resultType="Sysuser ">
select * from Sysuser
where 1=1
<if test="name!=null"> and user_name like #{name}</if>
<if test="ageStart!=null"> and age>#{ageStart}</if>
<if test="ageEnd!=null"><![CDATA[ and age<=#{ageEnd}]]></if>
</select>
编写接口文件
public interface SysuserCustomMapper {
public Sysuser findSysuserById(String id) throws Exception;
}
编写test类
public void testFindSysuserById() throws Exception {
// 获取spring容器
applicationContext = new ClassPathXmlApplicationContext(new String[] {
"spring/applicationContext.xml", "spring/applicationContext-dao.xml"
});
SysuserCustomMapper sysuserCustomMapper = (SysuserCustomMapper) applicationContext
.getBean("sysuserCustomMapper");
Sysuser sysuser = sysuserCustomMapper.findSysuserById("286");
System.out.println(sysuser);
}
使用MapperFactoryBean需要在spring容器对每个mapper进行配置,麻烦。
第四种 :
利用代码生成工具(就是一个java工程)
4444444.png
1、将接口文件、mapper.xml、实体类文件拷贝到项目的相应包下即可。
2、在spring中配置mapper自动扫描器
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描包路径 ,如果扫描多个包路径,中间使用半角逗号分隔-->
<property name="basePackage" value="yycg.base.dao.mapper"/>
<!-- 配置SqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
3、编写测试类
private ApplicationContext applicationContext;
protected void setUp() throws Exception {
// 获取spring容器
applicationContext = new ClassPathXmlApplicationContext(new String[] {
"spring/applicationContext.xml", "spring/applicationContext-dao.xml"
});
}
protected void tearDown() throws Exception {
}
public void testFindSysuserById() throws Exception {
// 获取spring容器
applicationContext = new ClassPathXmlApplicationContext(new String[] {
"spring/applicationContext.xml", "spring/applicationContext-dao.xml"
});
SysuserCustomMapper sysuserCustomMapper = (SysuserCustomMapper) applicationContext
.getBean("sysuserCustomMapper");
Sysuser sysuser = sysuserCustomMapper.findSysuserById("286");
System.out.println(sysuser);
}
注意:mapper.xml和mapper.java同名且在一个目录
网友评论