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

//Student.java
package njpji.model;
public class Student {
	private String stuNo;
	private String stuName;
	private String stuSex;
	public Student() {
		super();
	}
	
	public Student(String stuNo, String stuName, String stuSex) {
		super();
		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;
	}
	@Override
	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

//StudentDao.java
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;
	}
	@Override
	public void addStudent(Student student) throws Exception {
		
	}
	@Override
	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()) {
			student.setStuName(res.getString(1));
			student.setStuNo(res.getString(2));
			student.setStuSex(res.getString(3));
		}
		res.close();
		sta.close();
		conn.close();
		return student;
	}

	@Override
	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);
		sta.executeUpdate();
		System.out.println("Delete Student Success");
		sta.close();
		conn.close();
	}
	@Override
	public List<Student> findStudents() throws Exception {
		return null;
	}
}

4) Write service layer for a function module.

IDeleteStduent.java interface

//IDeleteStduent.java
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
	@Override
	public void deleteStudent(String stuNo) throws Exception {
		//Invoke queries
		Student student = studentDaoImpl.queryStudent(stuNo);
		if(student!=null) {
			//Call deletion
			studentDaoImpl.deleteStudent(stuNo);
		}else {
			System.out.println("The student does not exist.");
		}
	}
	
}

5) Write Servlet implementation class to delete students

DeleteStudentServlet.java

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;
@WebServlet("/DeleteStudentServlet")
public class DeleteStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ApplicationContext context;
    public DeleteStudentServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		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
			deleteStu.deleteStudent(stuNo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	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

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:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p"
	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" />
	</bean>
</beans>

web.xml

<?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">
  <display-name>spring_web_project</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- Appoint spring ioc Location of containers -->
  <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- Configuration listener,For loading spring ioc container -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- To configure servlet -->
	<servlet>
		<servlet-name>deleteStudentServlet</servlet-name>
		<servlet-class>njpji.servlet.DeleteStudentServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>deleteStudentServlet</servlet-name>
		<url-pattern>/deleteStudentServlet</url-pattern>
	</servlet-mapping>
</web-app>

7) Write test pages

delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<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" />
</form> 
</body>
</html>

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