Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring framework + jdbcTemplate to realize the function of adding, deleting, changing and searching

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to use Spring framework + jdbcTemplate to achieve add, delete, change and search function". In daily operation, I believe many people have doubts about how to use Spring framework + jdbcTemplate to achieve add, delete, change and search function. Editor consulted all kinds of information and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer "how to use Spring framework + jdbcTemplate to achieve add, delete, change and search function". Next, please follow the editor to study!

SpringMVC architecture (Model (entity classes), Service,Controller layer)

Controller (receive parameters call business layer)-> Service (call persistence layer, handle business logic)-> Dao (interact with database)

1. IOC (inversion of control is a design idea, not a technology)

DI (dependency injection): a technical implementation of IOC thought

The IOC container is a container provided by Spring to hold Bean objects.

Bean management operation

1.Xml + comments

2.javaConfig + comments

Configure Bean:TODO through xml:

Configure Bean:TODO through javaConfig:

Configure Bean:TODO through annotations:

2. AOP (facing section)

Aspect-oriented programming idea. Horizontal call.

Eg: a log function, a lot of functional modules need to be used, you can write an aspect to do this.

Use @ Aspect to mark a normal class as an aspect.

Connection point: for example, the method that the log needs to work.

Target object: the object that the log needs to use.

1. Add dependency

Org.springframework spring-aop 5.3.8 org.aspectj aspectjweaver 1.9.7 runtime2.demo activity

Requirements: SpringIOC + JDBCTemplate to achieve simple database operations

1. Create a new Maven project and introduce Spring core 4 dependencies

Org.springframework spring-context 5.3.1 org.springframework spring-core 5.3.1 org.springframework spring-beans 5.3.1 org.springframework Spring-expression 5.3.1

Jdbc dependence

Org.springframework spring-jdbc 5.3.6 mysql mysql-connector-java 5.1.47

Junit5

Org.junit.jupiter junit-jupiter-api 5.3.2 test

two。 Create a SpringConfig configuration file (inject bean through JavaConfig)

Create the SpringConfig class and add @ Configuration marked as the configuration class.

Configure the Bean for the data source and JDBCTemplate.

/ * * @ author YonC * @ date 2021-9-2 * / @ Configurationpublic class SpringConfig {@ Bean public DataSource dataSource () {MysqlDataSource dataSource = new MysqlDataSource (); dataSource.setUrl ("jdbc:mysql://localhost:3306/test?useUnicode=ture&charactorEncoding=utf-8&serverTimezone=UTC"); dataSource.setUser ("root"); dataSource.setPassword ("123456"); return dataSource @ Bean public JdbcTemplate jdbcTemplate (DataSource dataSource) {return new JdbcTemplate (dataSource);}}

3. Create an MVC schema and create entity class objects corresponding to database fields

Entity class: StudentPO

Public class StudentPO {private Long id; private String name; private String age; public StudentPO () {} public StudentPO (String name, String age) {this.name = name; this.age = age;} public StudentPO (Long id, String name, String age) {this.id = id; this.name = name; 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 getAge () {return age;} public void setAge (String age) {this.age = age } @ Override public String toString () {return "StudentPO {" + "id=" + id + ", name='" + name +'\'+ ", age=" + age +'}';}}

4. Write Dao layer

Interface-oriented programming, firstly, the standard interface of Dao layer is defined, and four methods of adding, deleting, modifying and querying are defined.

/ * * @ author YonC * @ date 2021-9-2 * / public interface StudentDao {void addStudent (StudentPO student); void delStudentById (Long id); void updateStudent (StudentPO student); List selectStudent ();}

Implementation of interface

The @ Repository annotation injects StudentDao into the IOC container

@ Autowired automatically assembles JdbcTemplate objects, and JdbcTemplate objects have been instantiated in the SpringConfig file

/ * * @ author YonC * @ date 2021-9-2 * / @ Repositorypublic class StudentDaoImpl implements StudentDao {@ Autowired JdbcTemplate jdbcTemplate; / * * add Student * * / @ Override public void addStudent (StudentPO student) {jdbcTemplate.update ("insert into student (name,age) values (?)", student.getName (), student.getAge ()) } / * * Delete Student * * / @ Override public void delStudentById (Long id) {jdbcTemplate.update ("delete from student where id=?", id);} / * * modify Student * * / @ Override public void updateStudent (StudentPO student) {String sql = "UPDATE student SET name=?,age=? Where id =? "; Object [] args = {student.getName (), student.getAge (), student.getId ()}; jdbcTemplate.update (sql, args);} / * * query * * / @ Override public List selectStudent () {String sql =" select id,name,age from student " Return this.jdbcTemplate.query (sql, (rs, index)-> {StudentPO student = new StudentPO (); student.setId (rs.getLong ("id")); student.setName (rs.getString ("name")); student.setAge (rs.getString ("age"); return student;});}}

5. The addition, deletion, modification and query of Dao and database have been implemented. Use the Service layer to call the method of the Dao layer.

First define the interface of the Service layer

/ * * @ author YonC * @ date 2021-9-2 * / public interface StudentService {void addStudent (StudentPO student); void delStudentById (Long id); void updateStudent (StudentPO student); List selectStudent ();}

Interface implementation

@ Service declares the object in the IOC container

@ Autowired the StudentDao in the IOC container initializes the StudentDao object

/ * * @ author YonC * @ date 2021-9-2 * / @ Servicepublic class StudentServiceImpl implements StudentService {@ Autowired StudentDao studentDao; @ Override public void addStudent (StudentPO student) {studentDao.addStudent (student);} @ Override public void delStudentById (Long id) {studentDao.delStudentById (id);} @ Override public void updateStudent (StudentPO student) {studentDao.updateStudent (student) @ Override public List selectStudent () {return studentDao.selectStudent ();}}

6. Testing with Junit5 Unit Test

First get the StudentService object through the IOC container

Private AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext (SpringConfig.class); / / IOC container through Spring private StudentService studentService = applicationContext.getBean (StudentService.class)

test

/ * * @ author YonC * @ date 2021-9-2 * / class StudentServiceImplTest {private AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext (SpringConfig.class); / / IOC container through Spring private StudentService studentService = applicationContext.getBean (StudentService.class); @ Test public void testAddStudent () {studentService.addStudent ("zahngsna", "999"); System.out.println ("added successfully!") ;} @ Test public void testDelStudent () {studentService.delStudentById (3L); System.out.println ("deleted successfully!") ;} @ Test public void testUpdateStudent () {/ / modify the name of Student with id 3 to "wang" and age to 21 studentService.updateStudent (new StudentPO (1L, "wang", "28"); System.out.println ("modified successfully!") ;} @ Test public void testSelectStudent () {studentService.selectStudent (). ForEach (System.out::println);} at this point, the study on "how to use Spring framework + jdbcTemplate to add, delete, modify and query function" is over. I hope it can solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report