1.1 以Xml的方式访问数据库的案例
要以xml的方式访问数据库需要用到JdbcTemplate ,因为 JdbcTemplate(jdbc的模板对象)在Spring 中提供了一个可以操作数据库的对象
org.springframework.jdbc.core.JdbcTemplate。
以xml的方式访问数据库的案例主要是以下几个步骤:
(1) 创建user(对应的表)表并添加数据
CREATE TABLE USER(
id INT,
username VARCHAR(20),
PASSWORD VARCHAR(20)
)
INSERT INTO USER(id,username,PASSWORD) VALUES(1001,'jack','123');
INSERT INTO USER(id,username,PASSWORD) VALUES(1002,'rose','456');
INSERT INTO USER(id,username,PASSWORD) VALUES(1003,'tom','789');
(2) 创建maven工程后,在pom.xml中导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<!-- jdbc模板对象依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
<!-- mysql数据库的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- 连接池的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- 注解的依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- 用于测试的依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
(3)创建实体类
package com.qf.pojo;
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private String password;
}
(4)创建Mapper层的UserMapper接口及UserMapperImpl实现类
package com.qf.mapper;
import com.qf.pojo.User;
import java.util.List;
public interface UserMapper {
//查询所有
public List<User> findAll();
}
package com.qf.mapper.impl;
import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
//声明jdbc模板对象(jdbcTemplate),调用方法
private JdbcTemplate jdbcTemplate;
//set方法注入
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<User> findAll() {
//准备sql语句
String sql ="select id,name,password from t_user";
//调用方法,query:查询
// update: 修改
// BeanPropertyRowMapper:是jdbcTemplate内封装好的对象,保存着由查询所有方法及实体类属性得到的查询数据
List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return users;
}
}
(5) 创建Service层的UserService接口以及UserServiceImpl实现类
package com.qf.service;
import com.qf.pojo.User;
import java.util.List;
public interface UserService {
public List<User> findAll();
}
package com.qf.service.impl;
import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import com.qf.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
// 声明userMapper
private UserMapper userMapper;
// set注入
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public List<User> findAll() {
return userMapper.findAll();
}
}
(6)创建controller层的UserController
package com.qf.controller;
import com.qf.pojo.User;
import com.qf.service.UserService;
import java.util.List;
public class UserController {
//声明userService
private UserService userService;
//提供set方法,在配置文件通过set方法注入
public void setUserService(UserService userService) {
this.userService = userService;
}
//创建findAll方法
public List<User> findAll(){
return userService.findAll();
}
}
(7) 创建jdbc.properties配置文件
db.username = root
db.password = root
db.driverClassName = com.mysql.cj.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/java2109?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
(8) 创建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 http://www.springframework.org/schema/context/spring-context.xsd">
<!--引入配置文件 将db.properties加载到配置文件用来连接数据库 -->
<!-- property-placeholder:引入外部配置文件
location:位置
classpath:当前src下的目录
-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 引入数据源(当前使用的数据连接池)
property:将对象的对应属性注入值
-->
<bean id="dataSoure" class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="url" value="${db.url}"></property>
<property name="driverClassName" value="${db.driverClassName}"></property>
</bean>
<!-- 创建JdbcTemplate对象-->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSoure"></property>
</bean>
<!-- Dao层-->
<bean id="userMapper" class="com.qf.mapper.impl.UserMapperImpl">
<property name="jdbcTemplate" ref="JdbcTemplate"></property>
</bean>
<!-- Service层-->
<bean id="userService" class="com.qf.service.impl.UserServiceImpl">
<property name="userMapper" ref="userMapper"></property>
</bean>
<!-- Controller层-->
<bean id="userController" class="com.qf.controller.UserController">
<property name="userService" ref="userService"></property>
</bean>
</beans>
(9)创建测试类SpringTest
package com.qf.test;
import com.qf.controller.UserController;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class SpringTest {
@Test
public void testFindAll() {
//加载配置文件,创建applicationContext对象
ClassPathXmlApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//获取Bean对象(即userController)
UserController userController =(UserController) applicationContext.getBean("userController");
//调用findAll方法
List<User> userList = userController.findAll();
System.out.println(userList);
}
}
(10) 测试结果
[User(id=1, name=jack, password=123), User(id=2, name=tom, password=456), User(id=3, name=rose, password=789)]
Process finished with exit code 0
2 以注解的方式访问数据库
(1)Spring中的注解
@Configuration
作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
@ComponentScan
作用:用于通过注解指定spring在创建容器时要扫描的包
属性:value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
等同于xml中: <context:component-scan base-package="com.qf"/>
@PropertySource
作用:用于指定properties文件的位置
属性:value:指定文件的名称和路径。
关键字:classpath,表示类路径下
等同于xml中: <context:property-placeholder location="classpath:jdbc.properties"/>
@Bean
作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性:name:用于指定bean的id。当不写时,默认值是当前方法的名称
细节:当我们使用注解配置方法时,如果方法有参数,在参数前加:
@Qualifier("@Bean注解中name的值"),spring框架会去容器中查找有没有可用的bean对象查找的方式和Autowired注解的作用是一样的。
@Import
作用:用于导入其他的配置类
属性:value:用于指定其他配置类的字节码。
当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
等同于xml中: <import resource="xxx.xml"></import>
(2) 创建user(对应的表)表并添加数据
CREATE TABLE USER(
id INT,
username VARCHAR(20),
PASSWORD VARCHAR(20)
)
INSERT INTO USER(id,username,PASSWORD) VALUES(1001,'jack','123');
INSERT INTO USER(id,username,PASSWORD) VALUES(1002,'rose','456');
INSERT INTO USER(id,username,PASSWORD) VALUES(1003,'tom','789');
(3) 创建maven工程后,在pom.xml中导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<!-- jdbc模板对象依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
<!-- mysql数据库的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- 连接池的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- 注解的依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- 用于测试的依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- 集成junit包
为了解决纯注解时找不到配置文件不好测试问题
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.10</version>
</dependency>
</dependencies>
(4) 创建jdbc.properties配置文件
db.username = root
db.password = root
db.driverClassName = com.mysql.cj.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/java2109?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
(5)创建SpringConfiguration.java作为注解配置类(==bean.xml)
package com.qf.config;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.Properties;
//指定当前类为配置类,优于其他类先执行,替换applicationContext.xml文件
@Configuration
//@PropertySource用于指定properties文件的位置
//引入配置文件,连接数据库
@PropertySource(value = "classpath:db.properties")
@ComponentScan("com.qf")//扫描对应包下的注解
public class SpringConfiguration {
//引入配置文件db.properties的属性、值
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
@Value("${db.url}")
private String url;
@Value("${db.driverClassName}")
private String driverClassName;
@Bean//把当前方法的返回值放在Spring容器中,相当于<bean id = "" class = "">
//为了不再单独写一个数据源,将数据源(连接池)封装到JdbcTemplate,返回JdbcTemplate获得数据源
public JdbcTemplate getJdbcTemplate(){
//创建properties对象,为了获取数据源
Properties properties = new Properties();
//设置对应参数,获得对应数据源的值
properties.setProperty("username",username);
properties.setProperty("password",password);
properties.setProperty("url",url);
properties.setProperty("driverClassName",driverClassName);
try {
//获取数据源
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
//返回Jdbc模版对象
return new JdbcTemplate(dataSource);
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("连接数据库异常");
}
}
(6)创建实体类
package com.qf.pojo;
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private String password;
}
(7)创建controller层的UserController
package com.qf.controller;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller//把当前类对象存入spring容器中
public class UserController {
@Autowired//按照类型自动注入
private UserService userService;
public User findById(Integer id){
return userService.findById(id);
}
}
(8)创建Mapper层的UserMapper接口及UserMapperImpl实现类
package com.qf.mapper;
import com.qf.pojo.User;
public interface UserMapper {
User findById(Integer id);
}
package com.qf.mapper.impl;
import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository//把当前类对象存入spring容器中
public class UserMapperImpl implements UserMapper {
@Autowired//按照类型自动注入
//引入jdbcTemplate,调用方法
private JdbcTemplate jdbcTemplate;
@Override
public User findById(Integer id) {
//准备sql语句
String sql = "select id,name,password from t_user where id = ?";
//调用方法,并返回查询数据
// query:查询
// update: 修改
// BeanPropertyRowMapper:是jdbcTemplate内封装好的对象,保存着由查询所有方法及实体类属性得到的查询数据
// 返回值是一个集合,加get(0)表示获取集合的第一个对象返回
return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class),id).get(0);
}
}
(9) 创建Service层的UserService接口以及UserServiceImpl实现类
package com.qf.service;
import com.qf.pojo.User;
public interface UserService {
User findById(Integer id);
}
package com.qf.service.impl;
import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service////把当前类对象存入spring容器中
public class UserServiceImpl implements UserService {
@Autowired//按照类型自动注入
//引入userMapper,调用方法
private UserMapper userMapper;
@Override
public User findById(Integer id) {
return userMapper.findById(id);
}
}
(10) 创建测试类SpringTast
package com.qf.test;
import com.qf.config.SpringConfig;
import com.qf.config.SpringConfiguration;
import com.qf.controller.UserController;
import com.qf.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)//集成Juint,测试纯注解访问数据库
//@ContextConfiguration(classes= SpringConfiguration.class)//引入配置类
@ContextConfiguration(classes= SpringConfig.class)//引入配置类
public class SpringTest {
//按照类型自动注入
@Autowired
//引入userController,调用方法
private UserController userController;
@Test
public void testFindById(){
User user = userController.findById(3);
System.out.println(user);
}
}
(11) 测试结果
[User(id=1, name=jack, password=123), User(id=2, name=tom, password=456), User(id=3, name=rose, password=789)]
Process finished with exit code 0
网友评论