Spring-based declarative transactions using annotations (database operations, servlet implementations)

Implementing declarative transactions with annotations (database operations, servlet implementations)
1. Transactions: Let's see how transactions in databases are defined.

That is to say, in a transaction, if many methods are invoked, either all of them are successfully executed or all of them fail to execute.
2. How to define a method as a transaction
1) Import the jar packages and add these jar packages on the basis of the six jar packages of the previous project:

2) Write Student instance class

package njpji.model;
public class Student {
	private String stuNo;
	private String stuName;
	private String stuSex;
	public Student() {
	public Student(String stuNo, String stuName, String stuSex) {
		this.stuNo = stuNo;
		this.stuName = stuName;
		this.stuSex = stuSex;

	public String getStuNo() {
		return stuNo;
	public void setStuNo(String stuNo) {
		this.stuNo = stuNo;
	public String getStuName() {
		return stuName;
	public void setStuName(String stuName) {
		this.stuName = stuName;
	public String getStuSex() {
		return stuSex;
	public void setStuSex(String stuSex) {
		this.stuSex = stuSex;
	public String toString() {
		return "Student [stuNo=" + stuNo + ", stuName=" + stuName + ", stuSex=" + stuSex + "]";

3) Write the Dao layer to realize the persistent operation of the database.

StudentDao.java interface

package njpji.dao;
import java.util.List;
import njpji.model.Student;
public interface StudentDao {
	//Adding students
	public void addStudent(Student student) throws Exception;
	//Query students
	public Student queryStudent(String stuNo) throws Exception ;
	//Delete students
	public void deleteStudent(String stuNo) throws Exception ;
	//Batch Query
	public List<Student> findStudents() throws Exception;

StudentDaoImpl.java implementation class

//StudentDaoImpl.java implements two methods of operating databases for testing and explaining
package njpji.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import org.apache.tomcat.jdbc.pool.DataSource;
import njpji.model.Student;
public class StudentDaoImpl implements StudentDao{
	private PreparedStatement sta = null;
	private Connection conn = null ;
	private ResultSet res = null;
	private DataSource dataSource;
	private Student student ;
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	public void setStudent(Student student) {
		this.student = student;
	public DataSource getDataSource() {
		return dataSource;
	public Student getStudent() {
		return student;
	public void addStudent(Student student) throws Exception {
	public Student queryStudent(String stuNo) throws Exception {
		String sql = "select * from user where name=?";
		conn = dataSource.getConnection();
		sta = conn.prepareStatement(sql);
		sta.setString(1, stuNo);
		res = sta.executeQuery();
		while(res.next()) {
		return student;

	public void deleteStudent(String stuNo) throws Exception {
		String sql = "delete from user where name=?";
		conn = dataSource.getConnection();
		sta = conn.prepareStatement(sql);
		sta.setString(1, stuNo);
		System.out.println("Delete Student Success");
	public List<Student> findStudents() throws Exception {
		return null;

4) Write service layer for a function module.

IDeleteStduent.java interface

package njpji.service;
public interface IDeleteStudent {
	//Delete students
	public void deleteStudent(String stuNo) throws Exception ;

DeleteStudentImpl.java Implementation Class: Delete Students
Implementing declarative annotations (@Transactional(readOnly = false) // Declaring transactions with annotations)

package njpji.service;
import org.springframework.transaction.annotation.Transactional;

import njpji.dao.StudentDaoImpl;
import njpji.model.Student;
public class DeleteStudentImpl implements IDeleteStudent{
	private StudentDaoImpl studentDaoImpl;
	public void setStudentDaoImpl(StudentDaoImpl studentDaoImpl) {
		this.studentDaoImpl = studentDaoImpl;

	//Delete student: first judge whether the student exists, does not exist, do not perform deletion operation, return false;
	//The student exists, performs the deletion operation, and returns true
	@Transactional(readOnly = false)  //Declare transactions with annotations
	public void deleteStudent(String stuNo) throws Exception {
		//Invoke queries
		Student student = studentDaoImpl.queryStudent(stuNo);
		if(student!=null) {
			//Call deletion
		}else {
			System.out.println("The student does not exist.");

5) Write Servlet implementation class to delete students


package njpji.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import njpji.service.IDeleteStudent;
public class DeleteStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ApplicationContext context;
    public DeleteStudentServlet() {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String stuNo = request.getParameter("stuNo");
		//Servlet global object generated when loading applicationContext.xml initialization
		context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		IDeleteStudent  deleteStu = (IDeleteStudent) context.getBean("deleteStudentImpl");
		try {
			//Call the method of deleting students
		} catch (Exception e) {
			// TODO Auto-generated catch block
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);

6) Write spring context profile and web profile


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<!-- Student.java -->
	<bean id="student" class="njpji.model.Student" ></bean>
	<!-- StudentDaoImpl.java -->
	<bean id="stuDaoImpl" class="njpji.dao.StudentDaoImpl" p:dataSource-ref="dataSource" p:student-ref="student"></bean>
	<!-- DeleteStudentImpl.java -->
	<bean id="deleteStudentImpl" class="njpji.service.DeleteStudentImpl" p:studentDaoImpl-ref="stuDaoImpl"></bean>
	<!-- Adding Transaction Support -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	<!-- Configuring Transaction Manager -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" ></bean>
	<!-- Configuration database correlation -->
	<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/test" />
		<property name="username" value="root"/>
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="password" value="caixibei" />
		<property name="maxActive" value="15"/>
		<property name="initialSize" value="5" />


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <!-- Appoint spring ioc Location of containers -->
	<!-- Configuration listener,For loading spring ioc container -->

	<!-- To configure servlet -->

7) Write test pages


<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html>
<meta charset="UTF-8">
<title>Test Page</title>
<body><form action="/spring_web_project/deleteStudentServlet">
//Please enter the student number you want to delete:<input type="text" name="stuNo" /><input type="submit" value="confirm deletion" />

8) Database

9) Screenshots
1. Delete the students. In fact, I made a mistake. I deleted them according to their names. Don't care about the details. Haha ha.

2. Change of database

Summary: read more code, write more familiar, no one is a genius, come on.

Tags: Java xml SQL Database

Posted on Wed, 09 Oct 2019 13:44:55 -0700 by nishmgopla