📄 driver.java
字号:
package org.hibernate.forum;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import net.sf.hibernate.FetchMode;
import net.sf.hibernate.FlushMode;
import net.sf.hibernate.LockMode;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.cfg.Environment;
import net.sf.hibernate.expression.Example;
import net.sf.hibernate.expression.Expression;
import net.sf.hibernate.expression.MatchMode;
public class Driver {
private SessionFactory factory;
/**
* viewPosts
*/
public void viewPosts(Long sellerId) throws Exception {
System.out.println("Viewing posts with the id: " + sellerId);
Session s = factory.openSession();
Transaction tx=null;
try {
tx = s.beginTransaction();
List list = s.createCriteria(Post.class)
.add( Expression.eq("id", sellerId) )
.list();
if (list.size()==0) throw new IllegalArgumentException("No posts for the given id: " + sellerId);
Post post = (Post) list.get(0);
System.out.println(
"ID: " + post.getId() + " - " + post.getPostAuthor() +
", MSG: " + post.getPostMsg()
);
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
s.close();
}
}
/**
* createTestPosts
*/
public void createTestPosts() throws Exception {
System.out.println("Setting up a test post");
Session s = factory.openSession();
Transaction tx = s.beginTransaction();
Category cat = new Category();
cat.setCategoryMsg("Rock Bands");
cat.setDescription("Talk about your favorite rock bands here!");
s.save(cat);
Topic top = new Topic();
Long lg = cat.getId();
top.setTopicMsg("Van Halen is back!");
top.setTopicAuthor("Joe User");
top.setCategoryID(lg);
s.save(top);
Post post = new Post(top.getId());
post.setPostDate(new java.sql.Date(System.currentTimeMillis()));
post.setPostMsg("They will be in my town today!!!");
post.setPostAuthor("Joe User");
s.save(post);
tx.commit();
s.close();
viewPosts(post.getId());
System.out.println("Done");
}
public static void main(String[] args) throws Exception {
final Driver test = new Driver();
Configuration cfg = new Configuration()
.addClass(Category.class)
.addClass(Post.class)
.addClass(Topic.class);
test.factory = cfg.buildSessionFactory();
test.createTestPosts();
test.factory.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -