欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernate 简单CRUD操作

程序员文章站 2022-07-14 12:26:19
...
首先我们要搭建好hibernate的开发环境 我是在Eclipse下搭建的
建立javaProject
下载hibernate3.2
加入jar包
从下载过来的hibernate3.2文件中COPY一份hibernate.cfg.xml 写上你的数据库配置
搭建日志环境.


hibernate中对实体的CRUD操作 建立了两个实体类 其关系在数据库中是ManyToMany的两张表
[b]pojo:Person[/b]

package com.test.bean;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Cascade;

@Entity
@Table(name="person1")
public class Person {
@Id
@Column(name="personId",length=10)
@GeneratedValue(strategy= GenerationType.AUTO)
private int personId;
@Column(name="userName",length=60)
private String userName;
@Column(name="password",length=60)
private String password;
/**TIMESTAMP :等于java.sql.Timestamp*/
@Temporal(TemporalType.TIMESTAMP)
private Date birthday;
/**
* ManyToMany 主控方配置
* 其实既然是所谓的多对多就无所谓的被控和主控了
* 这样配置我可以通过删除person 做到删除friend 但是无法通过删除friend 做到删除person
* 所以个人认为实应该两边都配置成主控方 希望大家来讨论
* 不知道为什么 这里写成CascadeType.PERSIST,CascadeType.MERGE} 不能做到联机更新
* 利用sesson.persist()估计能做到联机更新 这个我没去测试, 有时间下次做吧
* fetch=FetchType.LAZY 延迟加载
*/
@ManyToMany(fetch=FetchType.LAZY)
@Cascade(value={CascadeType.SAVE_UPDATE})
/**name-中间表名称 JoinTable-描述了MTM的数据表关系 joinColumns-定义中间表与person(当前类)的外键关系 inverseJoninCoulums-定义了中间表与另一端的外键关系*/
@JoinTable(name="person_friend",joinColumns={@JoinColumn(name="p_id")},inverseJoinColumns={@JoinColumn(name="f_id")})
Set<Friend> friend = new HashSet<Friend>();

/**getter setter*/
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Set<Friend> getFriend() {
return friend;
}
public void setFriend(Set<Friend> friend) {
this.friend = friend;
}



}


[b]pojo:Friend[/b]

package com.test.bean;

import java.util.HashSet;
import java.util.Set;

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.ManyToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name="friend1")
public class Friend {
@Id
@Column(name="friendId",length=10)
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer friendId;
@Column(name="fName",length=60)
private String fName;
@Column(name="fPass",length=60)
private String fPass;
/**ManyToMany 被控方的配置 */
/**
* mappedBy 属性定义了此类为双向关系的维护端 它的值应该是此关系的另一端的属性名(可见Person类中定义的friend)
*/
@ManyToMany(fetch=FetchType.LAZY,mappedBy="friend")
@Cascade(value={CascadeType.SAVE_UPDATE})
Set<Person> person = new HashSet<Person>();
public Integer getFriendId() {
return friendId;
}
public void setFriendId(Integer friendId) {
this.friendId = friendId;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getfPass() {
return fPass;
}
public void setfPass(String fPass) {
this.fPass = fPass;
}
public Set<Person> getPerson() {
return person;
}
public void setPerson(Set<Person> person) {
this.person = person;
}
}

CRUD---

package com.test.testBean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import com.test.bean.Friend;
import com.test.bean.Person;

public class TestPerson {
private static SessionFactory sessionFactory;
private static Transaction ts;
private Date date = new Date();
/**
* 构造方法 里面 创建sessionFactory
*/
public TestPerson(){
@SuppressWarnings("unused")
Session session = null;
try{
/** SchemaExport 每次都会将表的数据清空*/
//new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
//sessionFactory
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
System.out.println("创建sessionFactory成功");
}catch(Exception e){
e.printStackTrace();
System.out.println("创建sessionFactory出错");
}finally{

}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
TestPerson tp = new TestPerson();
//tp.addPF();
//tp.query();
//tp.update();
tp.testRemove();
}
/**
* 填充数据
* @throws Exception
*/
public void addPF() throws Exception{
Person p = new Person();
Friend f = new Friend();
p.setBirthday(date);
p.setPassword("fffff");
p.setUserName("fff");
//---------=============-------------------
f.setfName("FFFFFF");
f.setfPass("FFFFFFF");
this.save(p, f);
}
/**
* 建立关系 并且保存到数据库
* @param p person对象
* @param f friend 对象
* @return boolean
*/
public void save(Person p,Friend f)throws Exception{
p.getFriend().add(f);
/**
* 这里需要注意下 如果你的f是被控方 那么在save的时候 能save两张表的数据 但是不能建立关系
* 即中间表中没有数据
*/
Session session = sessionFactory.getCurrentSession();
org.hibernate.Transaction ts = session.beginTransaction();
// session.save(f);
//session.persist(arg0)
try{
session.save(p);
System.out.println("保存成功");
ts.commit();
}catch (Exception e) {
e.printStackTrace();
System.out.println("保存失败");
ts.rollback();
}
}
/**
* 查询数据
* @throws SecurityException
* @throws IllegalStateException
* @throws RollbackException
* @throws HeuristicMixedException
* @throws HeuristicRollbackException
* @throws SystemException
*/
@SuppressWarnings({ "unchecked", "static-access"})
public void query() throws SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException{
/**定义hql*/
String hql="from Person";
/**获得session*/
Session session = this.sessionFactory.getCurrentSession();
/**开始事务*/
ts = (Transaction) session.beginTransaction();
/**执行hql语句*/
Query query = session.createQuery(hql);
/**定义一个list来存放数据*/
List<Person>list = new ArrayList<Person>();
list = query.list();
/**遍历LIST*/
for(Person p: list){
System.out.println(p.getPassword());
System.out.println(p.getUserName());
}
/**事务提交*/
ts.commit();
/**关闭session ts*/
this.closeSession(session, ts);

}
/**
* 根据ID查询出对象--person
* @param personId
* @return
*/
@SuppressWarnings("static-access")
public Person queryPersonById(int queryId,String queryHql){
Session session = this.sessionFactory.getCurrentSession();
ts = (Transaction) session.beginTransaction();
Query query = session.createQuery(queryHql);
query.setInteger(0, queryId);
Person person =(Person) query.list().get(0);
return person;
}
/**
* 根据ID查询出对象--friend
* @param personId
* @return
*/
@SuppressWarnings("static-access")
public Friend queryFriendById(int queryId,String queryHql){
Session session = this.sessionFactory.getCurrentSession();
ts = (Transaction) session.beginTransaction();
Query query = session.createQuery(queryHql);
query.setInteger(0, queryId);
Friend friend =(Friend) query.list().get(0);
return friend;
}
/**
* 更新对象
* @throws Exception
*/
@SuppressWarnings("static-access")
public void update()throws Exception{
/**首先查询出对象*/
//定义查询语句
String queryHql="from Person p where p.personId=?";
Person person = queryPersonById(5,queryHql);
person.setPassword("update--paw123");
person.setUserName("update--pserson--Lyvee");
Session session = this.sessionFactory.getCurrentSession();
ts=session.beginTransaction();
try{
session.update(person);
ts.commit();
System.out.println("更新成功!!!");
}catch(Exception e){
e.printStackTrace();
//事务回滚
ts.rollback();
System.out.println("更新出错啦!!!");
}
finally{
this.closeSession(session, ts);
}
}
/**
* 删除方法---通过person删除
* @param person
* @throws Exception
*/
@SuppressWarnings("static-access")
public void del(Person person)throws Exception{
Session session = this.sessionFactory.getCurrentSession();
ts=session.beginTransaction();
try{
/**在此 由于我把person配置成了主控制方 故此删除person 由于没有配置联级删除故此被控方Friend仍然会存在 但是中间表记录会删除----关系不存在*/
session.delete(person);
ts.commit();
System.out.println("删除成功!");
}catch(Exception e){
e.printStackTrace();
//回滚事务
ts.rollback();
System.out.println("删除失败");
}finally{
this.closeSession(session, ts);
}
}
public void del(Friend friend){
Session session = this.sessionFactory.getCurrentSession();
ts=session.beginTransaction();
try{
/**这里由于friend是被控方 直接删除friend 会报错 我们应该首先断关系 然后delete*/
Set<Person> persons = friend.getPerson();
for(Person person :persons){
person.getFriend().remove(friend);
}
session.delete(friend);
ts.commit();
System.out.println("删除成功");
}catch (Exception e) {
e.printStackTrace();
System.out.println("删除失败");
ts.rollback();
}finally{
this.closeSession(session, ts);
}
}
/**
* 测试删除的方法
* @throws Exception
*/
public void testRemove() throws Exception{
Session session = this.sessionFactory.getCurrentSession();
ts=session.beginTransaction();
/**根据ID查询出person对象*/
//Person person = (Person) session.get(Person.class,1);
Friend friend = (Friend) session.get(Friend.class, 4);
// del(person);
del(friend);
}
/**
* session transacation 关闭
* @param session
* @param ts
* @return boolean
*/
public boolean closeSession(Session session,Transaction ts){
if(ts!=null){
ts=null;
}
return false;
}
}