Hibernate 注解配置实体类

一、注解配置实体类  

  Hibernate 注解配置实体类_第1张图片

   (1)写具体的实体类

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity    //持久化类
@Table(name="my_student")  //指定数据库表名
@NamedQuery(name="stu" ,query="from Student")  //HQL
public class Student {
	@Id     //PK
//	@GeneratedValue //序列化  hibernate自动序列 +1
//	@GeneratedValue(strategy=GenerationType.AUTO)   // hibernate自动序列 +1
//	@GeneratedValue(strategy=GenerationType.SEQUENCE) // *10,+10
	
	//使用自定义的序列化my_sid
	@SequenceGenerator(name="qq",sequenceName="my_sid")
	@GeneratedValue(generator="qq")
	private int id;
	
	@Column(name="sname")   //对应的列名
	private String name;
	
	private int age;
	
	@Transient   //不写入到数据表中
	private String address;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Student(int id, String name, int age, String address) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
	}

	public Student() {
		super();
	}

	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;<pre name="code" class="java">
}

 
   (2)在hibernate.cfg.xml中配置注解类 
 

<mapping class="com.hlx.entity.Student"/>

  (3)在hibernate.cfg.xml中配置创建表

  <!-- 自动创建表 -->
<property name="hbm2ddl.auto">update</property>


  (3)测试类

  

	@Test
	public void test1() {
		Session session = HibernateUtil.currentSession();
		Transaction tx = session.beginTransaction();

		try {
//			Student student = new Student(1000, "香菱", 21, "HZ");
			
			//配置序列化
//			Student student = new Student("郑书磊", 23);
			
//			Student student = new Student("mike", 21);
			
			Student student = new Student("xx", 22);

			session.save(student);
			tx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}

	}


	}
	
	
	


你可能感兴趣的:(Hibernate 注解配置实体类)