Spring中万物皆bean,包括数据库资源。Spring数据库编程中,Spring为我们提供了简单易用的数据库连接接口,我们只要提供driverclassname、url、username、password即可帮我们返回一个连接对象,而不需要原生的JDBC连接那么繁琐。
Spring中将数据源转化成bean的方式有:
这里分别举例用DriverManagerDataSource与DRUID的连接案例,其他的连接池大同小异,除了C3P0需要注意以下,它的数据源配置的属性名除了password全和其他的不一样。
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.0.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.0.5.RELEASEversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.22version>
dependency>
dependencies>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/example?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
bean>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.4version>
dependency>
<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/example?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
bean>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.0.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.0.5.RELEASEversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.22version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.4version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.6version>
dependency>
dependencies>
其中mybatis-spring就是spring与mybatis框架的整合包,让spring框架替我们生成SqlSessionFactory对象,而不用我们自己去写。
public class Account {
private int id;
private String name;
private double money;
public int getId() {
return id;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
public interface AccountMapper {
@Select("select * from account")
List<Account> select();
@Insert("insert into account values(#{id},#{name},#{money})")
void add(Account account);
@Delete("delete from account where id=#{id}")
void delete(int id);
@Update("update account set name=#{name},money=#{money} where id=#{id}")
void update(Account account);
}
public interface AccountService {
List<Account> select();
void add(Account account);
void delete(int id);
void update(Account account);
}
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
AccountMapper accountMapper;
@Override
public List<Account> select() {
return accountMapper.select();
}
@Override
public void add(Account account) {
accountMapper.add(account);
}
@Override
public void delete(int id) {
accountMapper.delete(id);
}
@Override
public void update(Account account) {
accountMapper.update(account);
}
}
<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
bean>
第二布,让Spring替我们产生SqlSessionFactory对象
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource2"/>
bean>
第三步,mybatis自动替我们产生mapper映射对象,怎么注入到spring中的bean里?直接用mapper接口的话会报错。因为spring中的bean要求一定要是类,不能是接口,而在使用mybatis时,我们的mapper只是个接口。这时候,我们要使用mybatis的mapper工厂,将我们需要的mapper接口交给工厂,让工厂帮我们产生对应的实现类,再放入到spring中的bean里。
<bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.example.mapper.AccountMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
bean>
这种方式,当我们真正开发项目的时候,会有大量的Mapper接口,如果我们要一个个地配置,就算是复制粘贴,也十分繁琐。这时候就要使用,mybatis的包扫描器来自动完成了。只要指定mapper所在的包,就可以对该包中的所有mapper完成扫描自动产生mapper接口的实现类,非常方便。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
bean>
还有另外一种方式,同样是包扫描的方式,但是看起来简洁一点,不过要事先导入mybatis命名空间,图中画框的就是声明该命名空间可用。
<mybatis-spring:scan base-package="com.example.mapper"/>
最后还有spring自身注解用的包扫描配置
<context:component-scan base-package="com.example"/>
测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MyTest {
@Autowired
DataSource dataSource2;
@Test
public void test1(){
System.out.println(dataSource2);
}
@Autowired
AccountService accountService;
@Test
public void testSelect() {
List<Account> accounts = accountService.select();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testadd() {
Account account = new Account();
account.setId(15);
account.setName("tomy");
account.setMoney(9999999999.0);
accountService.add(account);
testSelect();
}
@Test
public void testUpdate() {
Account account = new Account();
account.setId(15);
account.setName("tomy");
account.setMoney(8888888888888.0);
accountService.update(account);
testSelect();
}
@Test
public void testDelete() {
accountService.delete(15);
accountService.select();
}
}
spring整合mybatis是ssm框架中非常重要的一步,需要多加练习,牢牢巩固。在掌握spring整合mybatis框架后,可进一步学习spring的事件处理。