提示:本文章代码基本来自gitbook.cn的教程《精通Sringboot 42 讲》,作者纯洁的微笑。我写这篇文章的原因是因为原文代码直接在本地跑不通,需要添加一些代码,做一些修改才能完美运行,所以将修改后的版本分享出来,原教程还是不错的,附上链接精通springboot42讲。
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
com.alibaba
druid
1.0.9
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.primary.username=root
spring.datasource.primary.password=
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.secondary.username=root
spring.datasource.secondary.password=
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Primary//注意这里要加此注解以免依赖冲突
@Bean(name="primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate (
@Qualifier("primaryDataSource") DataSource dataSource ) {
return new JdbcTemplate(dataSource);
}
@Bean(name="secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar(32) DEFAULT NULL COMMENT '用户名',
`password` varchar(32) DEFAULT NULL COMMENT '密码',
`age` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
public class User {
private Long id;
private String name;
private String password;
private int age;
public User() {
}
public User(String name, String password, int age) {
this.name = name;
this.password = password;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
接口:
public interface UserRepository {
int save(User user,JdbcTemplate jdbcTemplate);
}
实现:
import com.kbdct.hello.jdbcL.entity.User;
import com.kbdct.hello.jdbcL.entity.UserRowMapper;
import com.kbdct.hello.jdbcL.resposity.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserRepositoryImpl implements UserRepository{
@Autowired
private JdbcTemplate primaryJdbcTemplate;
public int save(User user,JdbcTemplate jdbcTemplate) {
if(jdbcTemplate == null){
System.out.println("jdbcTemplate is null");
jdbcTemplate= primaryJdbcTemplate;
}
return jdbcTemplate.update("INSERT INTO users(name, password, age) values(?, ?, ?)",
user.getName(), user.getPassword(), user.getAge());
}
}
import com.kbdct.hello.jdbcL.entity.User;
import com.kbdct.hello.jdbcL.resposity.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Resource(name="primaryJdbcTemplate")//注意要用byname的方式注入
private JdbcTemplate primaryJdbcTemplate;
@Resource(name="secondaryJdbcTemplate")//注意要用byname的方式注入
private JdbcTemplate secondaryJdbcTemplate;
@Test
public void testSave2() {
User user =new User("smile","123456",30);
System.out.println("before call primaryJdbcTemplate");
userRepository.save(user,primaryJdbcTemplate);
System.out.println("before call secondaryJdbcTemplate");
userRepository.save(user,secondaryJdbcTemplate);
}
}
运行完测试例后可在两个数据库中看到插入的记录。
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import javax.sql.DataSource;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名
dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setInitialSize(2);//初始化时建立物理连接的个数
dataSource.setMaxActive(20);//最大连接池数量
dataSource.setMinIdle(0);//最小连接池数量
dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
return dataSource;
}
}
过去的两个月公司项目赶进度,我比较忙碌,没有写总结文章了,也偷懒了两个月下班后没学什么东西,这种状态可不行,我要stay hungry,我要学学学!但是过去两个月也不是完全没收获,写了一套hive查询让我对大数据环境的运行与使用有了一定了解,还是挺高兴的。