JDBC -- transaction ORM (object relational database mapping) DAO (data access object)

Posted by starsol on Thu, 09 Dec 2021 09:32:42 +0100

Transaction
It exists in both SQL server and Mysql
It refers to the smallest unit to complete an application processing, which is composed of one or more statements operating on the database. If all operations are successful before submitting a failure, all operations will be cancelled and restored to the previous state.

1. Cases where transactions are not used
For example:
Perform the opposite operation on a field - addition and subtraction. One sql statement is addition and the other is subtraction. Originally, the two run together to maintain balance, but one of the sql statements is wrong (word misspelling) If the execution is still in progress without error, it will cause the opposite expected consequences. At this time, the transaction is used to put the two together successfully before execution. Canceling a failure can well solve the problem

2. Specific usage transactions
Multiple operations in a transaction either succeed or fail
Through c.setAutoCommit(false); Turn off auto submit
Use c.commit(); Make a manual submission

The main thing is to put the sql language blocks that need to rely on transaction execution in c.setAutoCommit(false); And c.commit(); Between you

Code example:

static void nopreexecute(int count)
	{
		LinkedList list =new LinkedList();
		Scanner sd=new Scanner(System.in);
		try {
			Class.forName("com.mysql.jdbc.Driver");
		}catch(ClassNotFoundException s)
		{
			s.printStackTrace();
		}

		try(
				Connection c=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root","admin");
				Statement ps=c.createStatement()
				
				)
		{
			String st="";
			String  str="delete from hero where id= ?";
	     c.setAutoCommit(false);//From here on
	     
	     ResultSet rs=ps.executeQuery("select * from hero limit 0,"+count);
	     for (int i =1; i <=count; i++) {
	    	 while(rs.next())
	    	 {
	    		 int id=rs.getInt(1);
	    		 list.add(id);
	    		 System.out.println("Attempting to delete"+"id="+id+"Data");
	    	 }
		}
	     while(true)
	     {
	     System.out.println("Do you want to delete the data entry( Y/N)");
	     st=sd.nextLine();
	     
	     if(st.equalsIgnoreCase("Y"))
	     {
	    	 for (int i =1; i <=count; i++) {
	    		 PreparedStatement s=c.prepareStatement(str);
		    	s.setInt(1,(int) list.get(i-1));
		    	s.execute();
			}
	    	 System.out.println("Delete succeeded!");
	    	 break;
	    	
	     }
	     else if(st.equalsIgnoreCase("N"))
	     {
	    	 System.out.println("Deletion cancelled!");
	    	 break;
	     }
	     else
	     {
	    	 System.out.println("Incorrect character, please re-enter!");
	     }
	     }
	     c.commit();//Submit
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
	}

3. Note: the MYSQL table type must be INNODB to support transactions
In Mysql, transactions are supported only when the table type is INNODB, so you need to set the table type to INNODB, otherwise transactions cannot be observed

Modify the SQL of the table type INNODB:

alter table hero ENGINE = innodb;

View SQL for table type

show table status from how2java;

However, there is a premise that the current MYSQL server itself should support INNODB. If it does not support INNODB, you can configure it yourself

ORM-Object Relationship Database Mapping:
Example
After you need a design class, you can implement the object and database mapping by instantiating it in the JDBC test class
get method code example:

public static players get(int id)
	{
		players P=null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		}catch(ClassNotFoundException s)
		{
			s.printStackTrace();
		}

		try(
				Connection c=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root","admin");
				
				
				)
		{
	       String sql="select * from hero where id= ?";
	       PreparedStatement ps=c.prepareStatement(sql);
	        ps.setInt(1, id);
	        ResultSet sd=ps.executeQuery();
	      if(sd.next())
	        {
	        	P=new players();
	        	int Id=sd.getInt(1);
	        	String name=sd.getString(2);
	        	float hp=sd.getFloat(3);
	        	int damage= sd.getInt(4);
	        	P.id=Id;
	        	P.name=name;
	        	P.speed=hp;
	        	P.patience=damage;
	        }
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		return P;
	}

Design - players

public class players {
	public int id;
  public String name;
  public float speed;
  public int patience;
  }

The general idea of ORM is the above example

DAO-DataAccess Object
The essence is to put the design method in the interface with user-defined name and define a design class to implement it
Interface

The user-defined design class has already connected with the specified database when instantiating the class object and calling the parameterless construction method. It is not necessary to drive the connection every time the method is called, so the convenience is that the instantiated object reference can directly call the method of the implemented interface

ORM is the basis of DAO. DAO - Data Access Object - is the data in the database to access some attributes of the object, etc

Of course, the data of the object can also be written to the database

Topics: Database SQL Server JDBC SQL