Spring_IoC_annotation
2.导入必备jar包
pom.xml配置如下:
pom.xml
<?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.Taking</groupId>
<artifactId>spring_xml</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
4.编写实体类,业务层和持久层的接口和实现类
4.1 新建Package,编写代码
4.1.1在src/main/java目录下,新建一个名为com.Taking.domain的包(编写实体类),再在包中新建一个名为Student的类,代码如下:
Student.java
package com.Taking.domain;
import java.io.Serializable;
public class Student implements Serializable {
private Integer sNo;
private String sName;
private String sSex;
private Integer sAge;
private String sDept;
public Integer getsNo() {
return sNo;
}
public void setsNo(Integer sNo) {
this.sNo = sNo;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getsSex() {
return sSex;
}
public void setsSex(String sSex) {
this.sSex = sSex;
}
public Integer getsAge() {
return sAge;
}
public void setsAge(Integer sAge) {
this.sAge = sAge;
}
public String getsDept() {
return sDept;
}
public void setsDept(String sDept) {
this.sDept = sDept;
}
@Override
public String toString() {
return "Student{" +
"sNo=" + sNo +
", sName='" + sName + '\'' +
", sSex='" + sSex + '\'' +
", sAge=" + sAge +
", sDept='" + sDept + '\'' +
'}';
}
}
4.1.2在src/main/java目录下,新建一个名为com.Taking.dao的包(编写持久层的接口),再在包中新建一个名为StudentDao的接口,代码如下:
StudentDao.java
package com.Taking.dao;
import com.Taking.domain.Student;
import java.util.List;
public interface StudentDao {
List<Student> findAllStudent();
Student findStudentByNo(Integer sNo);
void saveStudent(Student student);
void updateStudent(Student student);
void deleteStudent(Integer sNo);
}
4.1.3在src/main/java目录下,新建一个名为com.Taking.dao.impl(编写持久层的实现类),再在包中新建一个名为StudentDaoImpl的类,代码如下:
StudentDaoImpl.java
package com.Taking.dao.impl;
import com.Taking.dao.StudentDao;
import com.Taking.domain.Student;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {
@Autowired
private QueryRunner runner;
public List<Student> findAllStudent() {
try {
return runner.query("select * from student", new BeanListHandler<Student>(Student.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Student findStudentByNo(Integer sNo) {
try{
return runner.query("select * from student where Sno = ? ",new BeanHandler<Student>(Student.class),sNo);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public void saveStudent(Student student) {
try{
runner.update("insert into student(Sno,Sname,Ssex,Sage,Sdept) values (?,?,?,?,?) ",
student.getsNo(),student.getsName(),student.getsSex(),student.getsAge(),student.getsDept(),student.getsName());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updateStudent(Student student) {
try{
runner.update("update student set Sname=?,Sex=?,Sage=?,Sdept=? where Sno=?",
student.getsName(),student.getsSex(),student.getsAge(),student.getsDept(),student.getsNo());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteStudent(Integer sNo) {
try{
runner.update("delete from student where Sno=?",sNo);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
4.1.4在src/main/java目录下,新建一个名为com.Taking.service的包(编写业务层的接口),再在包中新建一个名为StudentService的接口,代码如下:
StudentService.java
package com.Taking.service;
import com.Taking.domain.Student;
import java.util.List;
public interface StudentService {
List<Student> findAllStudent();
Student findStudentByNo(Integer sNo);
void saveStudent(Student student);
void updateStudent(Student student);
void deleteStudent(Integer sNo);
}
4.1.5在src/main/java目录下,新建一个名为com.Taking.service.impl的包(编写业务层的类),再在包中新建一个名为StudentServiceImpl的类,代码如下:
StudentServiceImpl.java
package com.Taking.service.impl;
import com.Taking.dao.StudentDao;
import com.Taking.domain.Student;
import com.Taking.service.StudentService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("studentService")
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
public List<Student> findAllStudent() {
return studentDao.findAllStudent();
}
public Student findStudentByNo(Integer sNo) {
return studentDao.findStudentByNo(sNo);
}
public void saveStudent(Student student) {
studentDao.saveStudent(student);
}
public void updateStudent(Student student) {
studentDao.updateStudent(student);
}
public void deleteStudent(Integer sNo) {
studentDao.deleteStudent(sNo);
}
}
5.编写数据库连接配置文件 jdbcConfig.properties
在src/main/resources目录下新建一个file,名为jdbcConfig.properties,内容如下:
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root
6.编写配置类
6.1 新建Package,编写代码
6.1.1 在src/main/java目录下,新建一个名为com.Taking.config的包(编写配置类),再在包中新建一个名为SpringConfiguration的类,代码如下:
SpringConfiguration.java
package com.Taking.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ComponentScan("com.Taking")
@Import(JdbcConfiguration.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
6.1.2 在src/main/java目录下,新建一个名为com.Taking.config的包(编写配置类),再在包中新建一个名为JdbcConfiguration的类,代码如下:
JdbcConfiguration.java
package com.Taking.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
public class JdbcConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "runner")
public QueryRunner getQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean(name = "dataSource")
public DataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
7.编写测试类
7.1 新建Package,编写测试代码
7.1.1 在src/test/java目录下,新建一个名为com.Taking.test的包(编写测试类),再在包中新建一个名为StudentServiceTest的类,代码如下:
StudentServiceTest.java
package com.Taking.test;
import com.Taking.config.SpringConfiguration;
import com.Taking.dao.StudentDao;
import com.Taking.domain.Student;
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;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class StudentServiceTest {
@Autowired
private StudentDao studentDao;
@Test
public void testFindAll() {
List<Student> students = studentDao.findAllStudent();
for (Student student : students) {
System.out.println(student);
}
}
@Test
public void testFindOne() {
Student student = studentDao.findStudentByNo(1);
System.out.println(student);
}
@Test
public void testSave() {
Student student = new Student();
student.setsNo(4);
student.setsName("赵六");
student.setsSex("女");
student.setsAge(16);
student.setsDept("艺传");
studentDao.saveStudent(student);
}
@Test
public void testUpdate() {
Student student = studentDao.findStudentByNo(4);
student.setsDept("外语");
studentDao.updateStudent(student);
}
@Test
public void testDelete() {
studentDao.deleteStudent(4);
}
}
8.测试结果
在这里就测试findAllStudent方法,结果如下图:
9.异常及解决方法
9.1 使用@Resource注解,需要手动导入javax.annotation
异常:
最开始在网上查找,提供了下面的dependency,运行后会出现如图所示异常
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
解决方法:
采用以下dependency,就没有异常出现了
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.1</version>
</dependency>
9.2 java.sql.SQLException:Access denied for user ‘lenovo’@localhost(using passwrod: YES)
异常:
添加jdbcConfig.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring
username=root
password=root
解决方法:
更改jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root
本文是基于注解方式实现Spring中IOC容器对数据库基本的CRUD的操作