关于Hibernate动态添加与修改

定义实体

package com.jlee06.QL;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
* @author JLee
* 主题
*/
@Entity
@Table(name="topic")
@NamedQueries({
@NamedQuery(name="Topic.selectTopic" , query="from Topic t where t.id = :id ") ,
@NamedQuery(name="Topic.conditionTopic" , query="from Topic t where t.title like :title ")
})
@org.hibernate.annotations.Entity(
dynamicInsert=true,
dynamicUpdate=true)
//hibernate3.3.2尚未支持
//@NamedNativeQueries({
// @NamedNativeQuery(name="native_sql_page" , query="select * from topic limit 2,5")
//})
public class Topic {

private int id ;
private String title ;
private Date createDate ;
public Date getCreateDate() {
return createDate;
}

@Column(name="createDate")
// @Temporal(TemporalType.DATE)
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
private Category category ;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

@Column(name="title" , length=32)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="categoryId")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}

}

 

执行的HQL语句

@Test
public void testInsert(){
Topic t = new Topic() ;
t.setTitle("insert") ;
Session session = sf.getCurrentSession() ;
Transaction tr = session.getTransaction() ;
tr.begin() ;
session.saveOrUpdate(t) ;
tr.commit() ;
}

@Test
public void testUpdate(){
Session session = sf.getCurrentSession() ;
Transaction tr = session.getTransaction() ;
tr.begin() ;
Topic t = new Topic() ;
t = (Topic)session.load(Topic.class, 1) ;//这里将数据库中的对象加载到内存
t.setCreateDate(new Date()) ;
session.saveOrUpdate(t) ;//执行这条语句之前会匹配哪一个字段与内存中的不一样,之后再进行更新
tr.commit() ;
}

你可能感兴趣的:(sql,Hibernate)