开始前还是说点废话,虽然上一篇已经写了Hibernate的小程序这次就不用写了,直接拷贝过来改改就行了,但是这样最终的目的还是达不到几天肯定就忘了hibernate的配置了为了熟练期间还是不厌其烦的从头再来。
第一步:新建Java项目用来Main测试hibernate的例子,创建项目包一共创建三个 com.ygc.hibernate.modle |com.ygc.hibernate.test | com.ygc.hibernate.utils分别解释下modle包用来存放bean对象的,test包用来写测试代码的就是main方法的,utils就是用来存放工具类的。本例中就不用手动创建表了,首先编写Modle类
package com.ygc.hibernate.modle; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Music") public class Music implements Serializable { private int id; private String musicName; private String author; private String musicType; @Id @GeneratedValue(strategy=GenerationType.AUTO) //主键自动增长 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMusicName() { return musicName; } public void setMusicName(String musicName) { this.musicName = musicName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMusicType() { return musicType; } public void setMusicType(String musicType) { this.musicType = musicType; } }
上面注意的地方要添加@Entity注解 Table指定表名 设置主键自动增长,主要的一点说清楚导包一定要导import javax.persistence.Entity;这个包,导入其他包会出现各种各样的问题。
第二步:编写main方法测试类
package com.ygc.hibernate.main; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.ygc.hibernate.modle.Music; import com.ygc.hibernate.utils.HibernateUtils; public class MusicTest { public static void main(String[] args) { Music music = new Music(); //id是自动增长的所以就不用在此处设置了 music.setAuthor("任贤齐"); music.setMusicName("爱的路上只有我和你"); music.setMusicType("浪漫型"); SessionFactory sFactory = HibernateUtils.getHibernateUtils().getSessionFactory(); Session session = sFactory.openSession(); session.beginTransaction(); session.save(music); session.getTransaction().commit(); session.close(); sFactory.close(); } }
第三步:编写工具类供主方法测试调用
package com.ygc.hibernate.utils; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static HibernateUtils instance; public static HibernateUtils getHibernateUtils(){ if(instance==null){ instance=new HibernateUtils(); } return instance; } public SessionFactory getSessionFactory(){ Configuration configuration = new AnnotationConfiguration().configure(); return configuration.buildSessionFactory(); } }
第四步:添加hibernate配置文件名称为hibernate.cfg.xml并且添加log4j的配置
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <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">root</property> <!-- JDBC connection pool (use the built-in) --> <!--<property name="connection.pool_size">1</property>--> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</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.internal.NoCacheProvider</property>--> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!--自动创建表--> <property name="hbm2ddl.auto">create</property> <!-- Drop and re-create the database schema on startup --> <!--<property name="hbm2ddl.auto">update</property>--> <!--<mapping resource="com/ygc/hibernate/modle/Students.hbm.xml"/>--> <mapping class="com.ygc.hibernate.modle.Music"/> </session-factory> </hibernate-configuration>
本例的重点说明下在配置中加了<property name="hbm2ddl.auto">create</property>这个配置才能创建属性值有好几个,分别有validate | update | create | create-drop
validate 加载hibernate时,验证创建数据库表结构
create 每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。
create-drop 加载hibernate时创建,退出是删除表结构
update 加载hibernate自动更新数据库结构
第五步:log4j的配置文件
# Configure logging for testing: optionally with log file # debug,info,warn,error,fatal log4j.rootLogger=debug, stdout, logfile log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.File=D:/logs/hibernate.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n log4j.logger.org.hibernate.tool.hbm2ddl=debug
第六步:查看运行结果。在cmd启动mysql 并且登陆mysql 在对应的数据库下面查看自己的表的数据
mysql> show tables; +---------------------+ | Tables_in_hibernate | +---------------------+ | music | | students | | teacher | | xuxudan | +---------------------+ 4 rows in set (0.06 sec)
mysql> select * from music; +----+--------+--------------------+-----------+ | id | author | musicName | musicType | +----+--------+--------------------+-----------+ | 1 | 任贤齐 | 爱的路上只有我和你 | 浪漫型 | +----+--------+--------------------+-----------+ 1 row in set (0.00 sec)
第七步:已经完了没有第七步了。最后把Demo给献上如果有bug请提出也给我一个学习的机会 谢谢。
Demo下载地址:下载 所用到的Jar包下载: jar包上传有点慢明晚共享出来...