基础的代码结构:
一个Application
作为入口。IUserRepository
和UserRepository
作为具体的实现。applicationContext.xml
定义spring的配置。db.properties
保存数据库相关的信息。
新建一个maven项目,编辑pom.xml
文件,如下。除了mysql的驱动,其他是必须的。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lou.spring.demo5.tx</groupId>
<artifactId>lou-spring-demo5-tx</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--spring的核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.25.RELEASE</version>
</dependency>
<!--orm相关,比如jdbctemplate-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.25.RELEASE</version>
</dependency>
<!--mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- datasource 数据源 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
</project>
在resources下面添加spring的配置文件applicationContext.xml
内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.无需定义repository注解,通过属性设置的方式进行-->
<bean id="userRepository1" class="com.lou.spring.demo5.tx.UserRepository">
<property name="jdbcTemplate" ref="dataSource"></property>
</bean>
<!-- 2.使用Component-scan的方式配合@repository注解-->
<!-- <context:component-scan base-package="com.lou.spring.demo5.tx"></context:component-scan>-->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.dirverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 上面datasource用到的属性值来自这个-->
<context:property-placeholder location="db.properties"></context:property-placeholder>
</beans>
在resources下面添加db.properties文件
jdbc.dirverClassName=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/test1?useSSL=false
添加IUserRepository和UserRepository用于数据库的访问。
IUserRepository.java
package com.lou.spring.demo5.tx;
public interface IUserRepository {
//显示总数
void showCount();
}
UserRepository.java
package com.lou.spring.demo5.tx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
@Repository
public class UserRepository implements IUserRepository {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setJdbcTemplate(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void showCount() {
Integer count = jdbcTemplate.queryForObject("select count(*) from account", Integer.class);
System.out.println(count);
}
}
component-scan
,然后spring自己去扫描查找需要的依赖。新建Application.java 作为程序入口。
package com.lou.spring.demo5.tx;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
BasicDataSource dataSource = (BasicDataSource) classPathXmlApplicationContext.getBean("dataSource");
//用来测试数据源是否通
System.out.println(dataSource);
//通过id的方式获取
UserRepository userRepository = (UserRepository) classPathXmlApplicationContext.getBean("userRepository1");
userRepository.showCount();
//通过class的方式获取
UserRepository userRepository1 = classPathXmlApplicationContext.getBean(UserRepository.class);
userRepository1.showCount();
}
}
先定义一个User对象
User.java
package com.lou.spring.demo5.tx;
public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
修改一下IUserRepository,增加如下内容。
public interface IUserRepository {
//总行数查询
Integer getTotalCount();
//带条件的总行数查询
Integer getTotalCount(String name);
//查询一个String
String getName();
//查询一个对象
User getUser();
//查询对象集合
List<User> getUsers();
}
具体实现:
@Repository
public class UserRepository implements IUserRepository {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setJdbcTemplate111(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Integer getTotalCount() {
Integer userCount = jdbcTemplate.queryForObject("select count(*) from user", Integer.class);
return userCount;
}
@Override
public Integer getTotalCount(String name) {
Integer louCount = jdbcTemplate.queryForObject("select count(*) from user where name like ?", Integer.class, name);
return louCount;
}
@Override
public String getName() {
String name = jdbcTemplate.queryForObject("select name from user where id=?", new Object[]{1}, String.class);
return name;
}
@Override
public User getUser() {
User user = jdbcTemplate.queryForObject("select * from user where id = ?", new Object[]{1}, new UserMapper());
return user;
}
@Override
public List<User> getUsers() {
List<User> users = jdbcTemplate.query("select * from user", new UserMapper());
return users;
}
//抽取公共的RowMapper<User>,内部私有的class,放外面的话是要public,非static
private static final class UserMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getInt("age"));
return user;
}
}
}
使用RowMapper对结果集做映射。UserMapper
是一个私有的静态类。使用的时候需要new。
@Override
public Integer insertUser(User u) {
return jdbcTemplate.update("insert into user (name,age) values(?,?)", u.getName(), u.getAge());
}
@Override
public Integer updateUser(Integer userId, String name) {
return jdbcTemplate.update("update user set name=? where id=?", name, userId);
}
@Override
public Integer deleteUser(Integer userId) {
return jdbcTemplate.update("delete from user where id = ?", userId);
}
用来执行create table 或者调用存储过程之类的sql语句。
this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
this.jdbcTemplate.update(
"call SUPPORT.REFRESH_ACTORS_SUMMARY(?)",
Long.valueOf(unionId));
JdbcTemplate
一旦被配置之后,他的实例就是线程安全的。这一点比较重要,因为这样你就可以把他注入到多个DAO或者Repository中。按照前文先配置DataSource,然后在构造函数里面实例化JdbcTemplate
。
新建项目,添加依赖,添加spring的xml配置文件,写repo,写application,获取bean,运行。