eclipse learning (Chapter 3: Hibernate in ssh) - 7 Hibernate uses annotation development

Posted by optiplex on Sun, 30 Jan 2022 23:14:36 +0100

preface

This article refers to https://www.w3cschool.cn/hibernate/zief1iev.html A practice note made after.

Project practice

1. Initialization project and jar package pull

2. mysql data structure

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for classes
-- ----------------------------
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
  `id` varchar(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `student_number` int(11) DEFAULT NULL,
  `teacher` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of classes
-- ----------------------------
INSERT INTO `classes` VALUES ('1', 'Every three years', '30', 'Lao Chen');
INSERT INTO `classes` VALUES ('2', 'Class two of four years', '42', 'Lao Li');
INSERT INTO `classes` VALUES ('3', 'Every five years', '35', 'Hollington ');

3. Create hibernate cfg. xml

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!--mysql Driver package for -->
		<property name="connection.driver_class">
			com.mysql.cj.jdbc.Driver
		</property>
		<!--Database connection address, where the database is passed in as a parameter, and;Separate different parameters-->
		<property name="connection.url">
			jdbc:mysql://localhost:3306/student?serverTimezone=UTC
		</property>
		<!--Database account-->
		<property name="connection.username">
			root
		</property>
		<!--Database password-->
		<property name="connection.password">
			root
		</property>
		<!--Database connection pool-->
		<property name="connection.pool_size">
			10
		</property>
		<!--Is it displayed in the log file sql-->
		<property name="show_sql">
			true
		</property>
		<!--set up Hibernate SQL dialect-->
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
	<!-- Actually, this hibernate.hbm2ddl.auto Parameter is mainly used for: automatic creation|to update|Verify the database table structure. If it is not the demand in this regard, suggestions set value="none".  -->
	<!-- create: Each load hibernate The last generated table will be deleted, and then according to your model Class to regenerate a new table, even if there is no change twice, it should be executed in this way, which is an important reason for the loss of database table data. -->
	<!-- create-drop :  Each load hibernate Time basis model Class generates a table, but sessionFactory One off,The table is automatically deleted.-->
	<!-- update: The most commonly used attribute is loaded for the first time hibernate Time basis model Class will automatically establish the structure of the table (the premise is to establish the database first) and load it later hibernate Time basis model Class automatically updates the table structure. Even if the table structure is changed, the rows in the table still exist and the previous rows will not be deleted. It should be noted that when deployed to the server, the table structure will not be established immediately. It will not be established until the application runs for the first time. -->
	<!-- validate :  Each load hibernate When validating the database table structure, it will only be compared with the tables in the database. No new table will be created, but new values will be inserted.-->
		<property name="hbm2ddl.auto">
			update
		</property>
		
		<mapping class="com.czx.annotations.pojo.Classes"/>
	</session-factory>
</hibernate-configuration>

4. Create entity Classes and use annotations to realize the correspondence of entity Classes. (please refer to the last point for the description of each annotation)

Classes

package com.czx.annotations.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "classes")
public class Classes {
	
	@Id 
//	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column
	private String id;
	
	@Column
	private String name;
	
	@Column(name = "student_number")
	private Integer studentNumber;
	
	@Column(name = "teacher")
	private String teacher;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getStudentNumber() {
		return studentNumber;
	}

	public void setStudentNumber(Integer studentNumber) {
		this.studentNumber = studentNumber;
	}

	public String getTeacher() {
		return teacher;
	}

	public void setTeacher(String teacher) {
		this.teacher = teacher;
	}

	public Classes(String id, String name, Integer studentNumber, String teacher) {
		this.id = id;
		this.name = name;
		this.studentNumber = studentNumber;
		this.teacher = teacher;
	}

	public Classes() {
	}

	@Override
	public String toString() {
		return "Classes [id=" + id + ", name=" + name + ", studentNumber=" + studentNumber + ", teacher=" + teacher
				+ "]";
	}

	
}

5. Create ClassesCURD to realize the addition, deletion, modification and query of short answer

ClassesCURD

package com.czx.annotations;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.czx.annotations.pojo.Classes;



public class ClassesCURD {
	private static SessionFactory sessionFactory;
	
	
	public static void main(String[] args) {
		try {
			//If you use the core package before hibernate 4, use this method to obtain the corresponding sessionFactory
//		sessionFactory =new AnnotationConfiguration().
//        configure().
//        //addPackage("com.czx.annotations.pojo") //add package if used.
//        addAnnotatedClass(Classes.class).
//        buildSessionFactory();
		
			
		//After hibernate4, the AnnotationConfiguration() method is removed. Configuration already contains annotation methods, so you can directly use:
		sessionFactory = new Configuration().configure().buildSessionFactory();
		}catch (Throwable t) {
			System.out.println("initialization sessionFactory Failed with exception:"+t);
			throw new ExceptionInInitializerError(t);
		}
		Classes classes = new Classes("6","A class in a certain year",60,"A class teacher");
		ClassesCURD classesCurd = new ClassesCURD();
		//Add test
		String a6 = classesCurd.addClasses(classes);
		System.out.println("Add result as"+a6);
		
		//Delete test
		String d1 = classesCurd.deleteClasses("1");
		System.out.println("The deletion result is"+d1);
		
		//Modify test
		Classes c2 = new Classes("6","A year B class",40,"X teacher");
		String u1 = classesCurd.updateClasses(c2);
		System.out.println("Modify test results:"+u1);
		
		//Find test
		List<Classes> classesList = classesCurd.listClasses();
		System.out.println("The query result is");
		for(int i = 0 ; i < classesList.size() ; i++) {
			System.out.println(classesList.get(i));
		}
		
	}
	
	//Add class and return value
	public String addClasses(Classes classes) {
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		String flag = null;
		try {
			transaction = session.beginTransaction();
			//What is returned here is actually the value of the primary key id
			flag = (String)session.save(classes);
			//Remember to submit the transaction, otherwise you can't add it
			transaction.commit();
		}catch(HibernateException he) {
			if(null != transaction) {
				transaction.rollback();
			}
			flag = null;
			he.printStackTrace();
		}finally {
			session.close();
		}
		return flag;
	}
	
	//Delete class
	public String deleteClasses(String classId) {
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		String flag = null;
		try {
			transaction = session.beginTransaction();
			Classes classes = session.get(Classes.class, classId);
			session.delete(classes);
			transaction.commit();
			flag = "success";
		}catch(HibernateException he) {
			if(null != transaction) {
				transaction.rollback();
			}
			flag = "fail";
			he.printStackTrace();
		}finally {
			session.close();
		}
		
		return flag;
	}
	
	//Modify class
	public String updateClasses(Classes classes) {
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		String flag = null;
		try {
			transaction = session.beginTransaction();
			session.update(classes);
			transaction.commit();
			flag = "success";
		}catch (HibernateException he) {
			if(null != transaction) {
				transaction.rollback();
			}
			flag = "fail";
			he.printStackTrace();
		}finally {
			session.close();
		}
		return flag;
	}

	//Query class
	public List<Classes> listClasses(){
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		List<Classes> classesList = null;
		try {
			transaction = session.beginTransaction();
			//When executing the query, the object name in the hql statement must be consistent with the class name of the entity class, which is strictly case sensitive. FROM entity class name
			List c = session.createQuery("from Classes").list();
			Iterator it = c.iterator();
			while(it.hasNext()) {
				Classes classes = (Classes)it.next();
				if(null == classesList && null != classes ) {
					classesList = new ArrayList<Classes>();
				}
				classesList.add(classes);
			}
			transaction.commit();
		}catch (HibernateException he) {
			if(null != transaction) {
				transaction.rollback();
			}
			classesList = null;
			he.printStackTrace();
		}finally {
			session.close();
		}
		return classesList;
	}
	
}

test

Just test your breakpoint. The normal output results are as follows.

Notable place

hibernate.cfg.xml if mapping here is teacher hbm. XML file, so this is it

<mapping resource="com/czx/demo/pojo/Teacher.hbm.xml"/>

If you use annotation mapping directly, this is the case

<mapping class="com.czx.annotations.pojo.Classes"/>

Various notes

@Entity annotation

  • EJB 3 standard annotations are included in javax Persistence package, I'll cut the package used in this project to see. So the first step is to import this package. In the second step, we use the @ Entity annotation on the Employee class, which indicates that this class is an Entity bean, so it must contain a constructor without parameters and be visible in the protected range.

@Table comments

  • @The table annotation allows you to specify the details of the table and ensure that the entity persists in the database.
  • @The table annotation provides four attributes that allow you to override the name, directory and schema of the table. In the table, you can make unique constraints on the columns. Now we are using a table named CLASSES.

@Id and @ GeneratedValue comments

  • Each entity bean has a primary key. You can annotate it with @ Id in the class. The primary key can be a field or a combination of multiple fields, depending on the structure of your table.
  • By default, the @ Id annotation will automatically determine the most appropriate primary key generation strategy, but you can override it by using the @ GeneratedValue annotation. Strategy and generator are two parameters that I will not discuss here, so we only use the default key generation strategy. Let Hibernate determine which generator types to use to migrate code between different databases.

@Column Annotation

  • @Column annotation is used to specify the details of the mapping between a column and a field or attribute. You can use the most common properties of the following comments:
    • The name attribute allows you to explicitly specify the name of the column.
    • The length property is the size of the column used to map a value, especially a string value.
    • The nullable attribute allows a column to be marked as non empty when generating a schema.
    • The unique attribute allows a column to contain only unique content

Extended reading

See here for more notes https://blog.csdn.net/dragonpeng2008/article/details/52297426

Project Download

Generally speaking, the above is enough. If you still can't understand it, you can download it here
https://gitee.com/mrchen13427566118/ssh_hibernate_learn.git
SSH here_ hibernate_ Annotations project is enough.
If you open it, you can see here https://blog.csdn.net/weixin_43987277/article/details/116936221

Topics: Hibernate