一步一步springboot_5.1 默认连接池

原创
10/14 17:01
阅读数 39

Spring Boot 2.0 以上默认使用 HikariCP。

驱动

see: https://www.cnblogs.com/liaojie970/p/8916568.html

  • com.mysql.jdbc.Driver 是 mysql-connector-java 5中的,
  • com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6 --新项目都用这个

mysql使用

1. application.properties

# spring.datasource.driver-class-name=com.mysql.jdbc.Driver (旧的)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://ip:port/db?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

2. pom.xml

<!-- mysql数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

3. 代码

  1. UserDao
@Component
public class UserDao {
	@Autowired
	JdbcTemplate template;

	private String createSql = "insert into user(name) values(?)";

	/**
	 * 返回id
	 * @param name
	 * @return
	 */
	public Integer create(String name){

		KeyHolder keyHolder = new GeneratedKeyHolder();;
		template.update(new PreparedStatementCreator(){
			@Override
			public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
				PreparedStatement ps = connection.prepareStatement(createSql, Statement.RETURN_GENERATED_KEYS);
				ps.setString(1,name);
				return ps;
			}
		}, keyHolder);

		//int update = template.update(createSql, name);
		return keyHolder.getKey().intValue();
	}
}
  1. 测试用例
@SpringBootTest(classes= StartUpApp.class)
@RunWith(SpringRunner.class)
public class AppTest {

	@Autowired
	private UserDao dao;

	@Test
	public void batchCreate() {
		for(int i=0; i<100;i++){
			int id = dao.create(UUID.randomUUID().toString());
			System.err.println(id);
		}
	}
}

oracle使用

1. application.properties

把之前mysql的配置注释掉

# oracle数据库
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@ip:port:xxxx
spring.datasource.username=xxxx
spring.datasource.password=xxxx

2. pom.xml

<!-- oracle数据库驱动 -->
<dependency>
    <groupId>com.oracle.ojdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>19.3.0.0</version>
</dependency>
<dependency>
    <groupId>com.oracle.ojdbc</groupId>
    <artifactId>orai18n</artifactId>
    <version>19.3.0.0</version>
</dependency>

3. 代码

  1. UserDao
@Component
public class OracleUserDao {
	@Autowired
	JdbcTemplate template;

	private String createSql = "insert into TEST_USER(id,name) values(sys_guid(),?)";

	/**
	 * 返回id
	 * @param name
	 * @return
	 */
	public void create(String name){
		template.update(createSql, name);
	}

}
  1. 测试用例
@SpringBootTest(classes= StartUpApp.class)
@RunWith(SpringRunner.class)
public class OracleTest {

	@Autowired
	private OracleUserDao oDao;


	@Test
	public void oracleBatchCreate() {
		for(int i=0; i<100;i++){
			oDao.create(UUID.randomUUID().toString());
		}
	}
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部