初学hibernate,基本配置
首先是导包
其中最后一个asm包,可谓是让我费劲又伤神啊。具体情况就不说了。
其次是配置hibernate.cfg.xml文件
我用的是微软SQL Server
<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name="connection.url">jdbc:sqlserver://localhost:1433;databaseName=student</property> <property name="connection.username">sa</property> <property name="connection.password">1111</property> <!-- JDBC connection pool (use the built-in) --> <!-- <property name="connection.pool_size">1</property> --> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.SQLServerDialect</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> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <!-- <mapping resource="yg/model/Stu.hbm.xml"/> --> <mapping class="yg.model.Stu" /> </session-factory> </hibernate-configuration>
因为我使用的是Annotation的配置,使用注解。因此没有配置xxx.hbm.xml文件
package yg.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Stu { private int id; private String name; private int age; public int getAge() { return age; } @Id public int getId() { return id; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } }
接下来就是TEST测试类
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import yg.model.Stu; public class StuTest { public static void main(String[] args) { Stu s = new Stu(); s.setId(1); s.setName("s1"); s.setAge(1); Configuration cfg = new AnnotationConfiguration(); SessionFactory sf = cfg.configure().buildSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.save(s); session.getTransaction().commit(); session.close(); sf.close(); } }
ok,配置hibernate就完成了。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。