环境:添加Jar包
mybatis-3.4.0.jar
mybatis-spring-1.3.0.jar
配置数据源
DataSource
SqlSessionFactory
TransactionManager
Mapper
1.连接参数:
在src下新建db.properties
datasource.connection.driver_class=com.mysql.jdbc.Driver
datasource.connection.url=jdbc:mysql://localhost:3307/db_ssm?useUnicode=true&characterEncoding=utf-8
datasource.connection.username=root
datasource.connection.password=123456
2.读取连接参数:
@PropertySource(value="classpath:db.properties")
public class MainCfg {
@Bean
public PropertySourcesPlaceholderConfigurer propertySource(){
return new PropertySourcesPlaceholderConfigurer();
}
……
}
3.创建数据源:
@Value("${jdbc.driver}")
private String driver;
@Value("${db.url}")
private String dburl;
@Value("${db.password}")
private String dbpwd;
@Value("${db.username}")
private String dbuser;
@Value("${}")
通过@Value("${}") 可以获取对应属性文件中定义的属性值。
(bean对象)
@Bean(destroyMethod="close")
public DataSource dataSource() throws PropertyVetoException{
ComboPooledDataSource ds=new ComboPooledDataSource();
ds.setJdbcUrl(dburl);
ds.setUser(dbuser);
ds.setPassword(dbpwd);
ds.setDriverClass(driver);
return ds;
}
(SessionFactory 对象)
@Bean
public SqlSessionFactory sessionFactory() throws Exception{
System.out.println(dburl);
SqlSessionFactoryBean sfb=new SqlSessionFactoryBean();
sfb.setDataSource(this.dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setConfigLocation(resolver.getResource("classpath:mybatis-cfg.xml"));
return sfb.getObject();
}
4.创建事务管理器
创建transactionManager对象:
@Bean
public DataSourceTransactionManager transactionManager() throws PropertyVetoException{
return new DataSourceTransactionManager(this.dataSource());
}
配置SQL映射
1. 扫描Mapper位置
xml配置中,使用MapperScannerConfigurer完成指定包下的Dao接口的代理工作:
在注解方式下,我们使用注解MapperScan完成指定包的扫描;
@MapperScan("com.icss.dao")
public class DbConfig {
……
}
2. 注解Mapper
<mapper namespace="com.ischoolbar.programmer.dao.admin.LogDao">
<!-- 日志插入操作 -->
<insert id="add" parameterType="com.ischoolbar.programmer.entity.admin.Log">
insert into log(id,content,createTime) values(null,#{content},#{createTime})
</insert>
<!-- 日志信息搜索查询 -->
<select id="findList" parameterType="Map" resultType="com.ischoolbar.programmer.entity.admin.Log">
select * from log
<if test="content != null">
where content like '%${content}%'
</if>
<if test="offset != null and pageSize != null">
limit #{offset},#{pageSize}
</if>
</select>
<!-- 模糊搜索总条数 -->
<select id="getTotal" parameterType="Map" resultType="Integer">
select count(*) from log
<if test="content != null">
where content like '%${content}%'
</if>
</select>
<!-- 删除日志信息 -->
<delete id="delete" parameterType="String">
delete from log where id in(${value})
</delete>
</mapper>