《注意:在配置时hibernate的下载的版本一定确保正确,因为不同版本导入的jar包可能不一样,所以会导致出现一些错误》

hibernate实现有两种配置,xml配置与注释配置。

(1):xml配置:hibernate.cfg.xml (放到src目录下)和实体配置类:xxx.hbm.xml(与实体为同一目录中)

<?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:3306/hxj

</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.NoCacheProvider

</property>

<!-- Echo all executed SQL to stdout -->

<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->

<!—update也可以用create/create-drop/update/validate代替, create 表示可以根据实体配置文件来自动生成表(只能生成表).

-->

<property name="hbm2ddl.auto">update</property>

// 实体配置类

<mapping resource="com/wsw/struts/model/Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

(2): 实体配置类:xxx.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package=”com.wsw.struts.model”>

<class name="Person" table="per">

<id name="id" column="id">

<generator class="native"/>   //字段自增

</id>

<property name="username" column="p_username"/>

<property name="age" column="p_age"/>

</class>

</hibernate-mapping>

(3):测试类(包括获取SessionFactory类和实体测试类)

SessionFactory类:HibernateUtil

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {

try {

// Create the SessionFactory from hibernate.cfg.xml

sessionFactory = new Configuration().configure().buildSessionFactory();

} catch (Throwable ex) {

// Make sure you log the exception, as it might be swallowed

System.err.println("Initial SessionFactory creation failed." + ex);

throw new ExceptionInInitializerError(ex);

}

}

public static SessionFactory getSessionFactory() {

return sessionFactory;

}

}

实体测试类:PersonManager

-----------------------------------------------------------------------------------

public class PersonManager {

public static void main(String[] args) {

createAndStorePerson();

HibernateUtil.getSessionFactory().close();

}

private static void createAndStorePerson() {

Session session =                   // 通过Session工厂获取Session对象

HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();         //开始事务

Person person = new Person();

person.setUsername("何小景");

person.setAge(26);

session.save(person);

session.getTransaction().commit(); // 提交事务

}

}

(4):注解方式:

注解的方式与xml很很多类似:

首先是需要加入4个jar包:hibernate-commons-annotations.jar 、 hibernate-annotations.jar

ejb3-persistence.jar 、 hibernate-jpa-2.0-api-1.0.1.Final.jar

下面是不同的地方:

(1):hibernate.hbm.xml 文件中把引用:xxx.hbm.xml改为引用实体类:

即把:<mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/>

改为:<mapping class="com.wsw.hibernate.model.Teacher" />

(2):获取SessionFactory方式发生了变化:

即:由SessionFactory sf = new Configuration().configure().buildSessionFactory()

改为:SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory()

(3):注解方式不需要在xxx.hbm.xml把实体类与表进行映射。而采用在实体类中进行注解。

注意:(1):如果实体类属性名与表字段名不一致的时候,要么都注解在属性前,要么都注解在get方法前。不能部分注解在属性前,部分注解在方法前。

(2):如果实体类属性名与表字段名一致的时候,可以部分注解在属性前,部分注解在方法前。

(3):如果在实体类中某些属性不注解:(属性和get都不写注解),默认为表字段名与实体类属性名一致。

(4):如果实体类的某个成员属性不需要存入数据库中,使用@Transient 进行注解就可以了。即类似于:(xxx.hbm.Xml配置中的某些字段不写(就是不需要对这个成员属性进行映射))

(5):表名称可以在实体类前进行注解。

(6):所有这些注解在:javax.persistence包下。而不是在hibernate包中。

---------------------------------------------------------------------------------------------------------------------

@Entity                        // 表示为实体类

@Table(name="t_teacher")       // 表名注解

public class Teacher implements Serializable {

private int id;

private String username;

private int age;

@Id              // 表示主键

@GenericGenerator(name = "generator", strategy = "increment")   @GeneratedValue(generator = "generator")   // 自增长

@Column(name = "id")                                 // 类属性对应着表字段

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(name="t_username")                       // 类属性对应着表字段

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

@Column(name="t_age")                      // 在实体类属性进行注解,类属性对应着表字段
    public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

《转自:http://www.blogjava.net/yxhxj2006/archive/2012/06/30/381861.html》

最新文章

  1. unity3d关于碰撞问题
  2. 如何在Eclipse中查看JDK的源代码
  3. HBase权威指南环境配置
  4. 备份U盘分区表,未雨绸缪
  5. postgresql - mac 启动 关闭 postgresql
  6. 使用 CocoStudio UI 编辑器实现《乱斗堂》设置界面
  7. css的优先级以及!important的使用
  8. 产生不重复的随机数TGUID
  9. C语言递归分析
  10. mysql日期函数 当前日期 curdate() , 当前年 year(curdate()), 取date的年份 year(date) ,取date的月份 month(date)
  11. Java Persistence/ManyToMany
  12. Vuex 存储||获取后台接口数据
  13. CSS制作镂空字体
  14. MySQL 约束、表连接、表关联、索引
  15. JavaScript深入之词法作用域和动态作用域
  16. JSX设置CSS样式详解
  17. Visual Studio Many Projects in One Solution VS中多工程开发
  18. Java连接Mysql数据库警告: Establishing SSL connection without server&#39;s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established
  19. Mac下必备快捷键的符号所对应的按键
  20. OSG使用模板缓存

热门文章

  1. linux内存查看及释放
  2. hive &amp; hive beeline常用参数
  3. 我的mac的其他满了,发现是一个叫core的文件
  4. [转]Handler学习笔记(一)
  5. docker 部署nginx+weblogic集群
  6. WCF客户端获取服务器返回数据报错
  7. Fork of LGPL version of JPedal
  8. div 边框
  9. eclipse的Maven项目pom.xml错误信息提示missingxxxjar解决方案
  10. Spring RestTemplate 小结