一、新建一个java工程名为:hibernate_0200;
二、导入必要的包:hibernate相关和junit4;
三、目录结构如图:
四、各个对应的类:
Category:
package com.bjsxt.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.BatchSize; @Entity public class Category { private int id; private String name; @Id @GeneratedValue 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; } }
Msg:
package com.bjsxt.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Msg { private int id; private String cont; private Topic topic; @ManyToOne public Topic getTopic() { return topic; } public void setTopic(Topic topic) { this.topic = topic; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCont() { return cont; } public void setCont(String cont) { this.cont = cont; } }
MsgInfo:
package com.bjsxt.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; public class MsgInfo { private int id; private String cont; private String topicName; private String categoryName; public MsgInfo(int id, String cont, String topicName, String categoryName) { super(); this.id = id; this.cont = cont; this.topicName = topicName; this.categoryName = categoryName; } public String getTopicName() { return topicName; } public void setTopicName(String topicName) { this.topicName = topicName; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCont() { return cont; } public void setCont(String cont) { this.cont = cont; } }
Topic:
package com.bjsxt.hibernate; import java.util.Date; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import org.hibernate.annotations.BatchSize; @Entity public class Topic { private int id; private String title; private Category category; private Date createDate; public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @ManyToOne public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">admin</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property> <property name="connection.username">scott</property> <property name="connection.password">tiger</property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> --> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- Drop and re-create the database schema on startup <property name="hbm2ddl.auto">update</property> --> <!-- <mapping resource="com/bjsxt/hibernate/Group.hbm.xml"/> <mapping resource="com/bjsxt/hibernate/User.hbm.xml"/> --> <mapping class="com.bjsxt.hibernate.Category"/> <mapping class="com.bjsxt.hibernate.Msg"/> <mapping class="com.bjsxt.hibernate.Topic"/> </session-factory> </hibernate-configuration>
log4j.properties:
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n ### direct messages to file hibernate.log ### #log4j.appender.file=org.apache.log4j.FileAppender #log4j.appender.file.File=hibernate.log #log4j.appender.file.layout=org.apache.log4j.PatternLayout #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=warn, stdout #log4j.logger.org.hibernate=info #log4j.logger.org.hibernate=debug ### log HQL query parser activity #log4j.logger.org.hibernate.hql.ast.AST=debug ### log just the SQL #log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ### #log4j.logger.org.hibernate.type=info #log4j.logger.org.hibernate.type=debug ### log schema export/update ### log4j.logger.org.hibernate.tool.hbm2ddl=debug ### log HQL parse trees #log4j.logger.org.hibernate.hql=debug ### log cache activity ### #log4j.logger.org.hibernate.cache=debug ### log transaction activity #log4j.logger.org.hibernate.transaction=debug ### log JDBC resource acquisition #log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ### ### leakages when using DriverManagerConnectionProvider ### #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
HibernateQLTest:
package com.bjsxt.hibernate; import java.util.Date; import java.util.Iterator; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class HibernateQLTest { private static SessionFactory sf; @BeforeClass public static void beforeClass() { sf = new AnnotationConfiguration().configure().buildSessionFactory(); } @AfterClass public static void afterClass() { sf.close(); } @Test public void testSchemaExport() { new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); } @Test public void testSave() { Session session = sf.openSession(); session.beginTransaction(); for(int i=0; i<10; i++) { Category c = new Category(); c.setName("c" + i); session.save(c); } for(int i=0; i<10; i++) { Category c = new Category(); c.setId(1); Topic t = new Topic(); t.setCategory(c); t.setTitle("t" + i); t.setCreateDate(new Date()); session.save(t); } for(int i=0; i<10; i++) { Topic t = new Topic(); t.setId(1); Msg m = new Msg(); m.setCont("m" + i); m.setTopic(t); session.save(m); } session.getTransaction().commit(); session.close(); } //list 与 iterate @Test public void testQuery5() { Session session = sf.openSession(); session.beginTransaction(); Iterator<Topic> topics = session.createQuery("from Topic").iterate(); while(topics.hasNext()){ System.out.println(topics.next().getTitle()); } Iterator<Topic> topics2 = session.createQuery("from Topic").iterate(); while(topics2.hasNext()){ System.out.println(topics2.next().getTitle()); } session.getTransaction().commit(); session.close(); } //list 与 iterate @Test public void testQuery6() { Session session = sf.openSession(); session.beginTransaction(); Iterator<Topic> topics = session.createQuery("from Topic").list().iterator(); while(topics.hasNext()){ System.out.println(topics.next().getTitle()); } Iterator<Topic> topics2 = session.createQuery("from Topic").list().iterator(); while(topics2.hasNext()){ System.out.println(topics2.next().getTitle()); } session.getTransaction().commit(); session.close(); } public static void main(String[] args) { beforeClass(); } }
五、运行如下: