本文共 3218 字,大约阅读时间需要 10 分钟。
package com.mycompany.demo.bean;public class Forum { private int fid; private String name; public Forum() { super(); } public Forum(int fid, String name) { super(); this.fid = fid; this.name = name; } public int getFid() { return fid; } public void setFid(int fid) { this.fid = fid; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
This class contains the forum detail.
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/b_shequ_two root update
package com.mycompany.demo.bean;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;public class ManageForum { /* * 添加操作 */ @Test public void addForum(){ Configuration configuration = new Configuration(); SessionFactory sf = configuration.configure().buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); tx.begin(); Forum forum = new Forum(); forum.setName("forumdemo"); session.save(forum); tx.commit(); session.close(); } /* * 根据ID查询 */ @Test public void findForumById(){ Configuration configuration = new Configuration(); SessionFactory sf = configuration.configure().buildSessionFactory(); Session session = sf.openSession(); Query query = session.createQuery("from Forum where fid = 57");//Forum是类名不是表名 Forum forum = (Forum) query.uniqueResult(); session.close(); System.out.println(forum.getName()); } /* * 更新Forum信息 */ @Test public void modifyForum(){ Configuration configuration = new Configuration(); SessionFactory sf = configuration.configure().buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); tx.begin(); Query query = session.createQuery("from Forum where fid = 57"); Forum forum = (Forum) query.uniqueResult(); forum.setName("modify"); session.persist(forum); tx.commit(); session.close(); } /* * 删除 */ @Test public void removeForum(){ Configuration configuration = new Configuration(); SessionFactory sf = configuration.configure().buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); tx.begin(); Query query = session.createQuery("from Forum where fid = 57"); Forum forum = (Forum) query.uniqueResult(); session.delete(forum); tx.commit(); session.close(); }}
转载地址:http://ghnkl.baihongyu.com/