JPA基础(二):JPA开发环境和思想介绍

开发JPA依赖的jar文件

注意jar文件不能放在含有中文或是含有空格的路径下,否则可能会出现找不到类或是编译失败的错误。


Hibernate核心包(8个文件):hibernate-distribution-3.3.1.GA.ZIP

 

hibernate3.jar
lib\bytecode\cglib\hibernate-cglib-repack-2.1_3.jar (CGLIB库,Hibernate用它来实现PO字节码的动态生成,非常核心的库,必须使用的jar包)
lib\required\*.jar


Hibernate注解包(3个文件):hibernate-annotations-3.4.0.GA.ZIP

 

hibernate-annotations.jar
lib\ejb3-persistence.jar, hibernate-commons-annotations.jar


Hibernate针对JPA的实现包(3个文件):hibernate-entitymanager-3.4.0.GA.ZIP

hibernate-entitymanager.jar
lib\test\log4j.jar, slf4j-log4j12.jar


Hiberante封装了JDBC,连接具体的数据库还需要具体数据库的JDBC驱动包,这里使用的是MySQL,需要MySQL数据库驱动包:
mysql-connector-java-5.0.8-bin.jar


JPA的配置文件

 

JPA规范要求在类路径(Eclipse工程的src目录)的META-INF目录下放置persistence.xml, 文件的名称是固定的,配置模板(此处是针对Hibernate)如下:

 1 <?xml version="1.0"?>
2 <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
3   <persistence-unit name="sample" transaction-type="RESOURCE_LOCAL">
4     <properties>
5       <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
6       <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
7       <property name="hibernate.connection.username" value="root"/>
8       <property name="hibernate.connection.password" value="123456"/>
9       <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/hibernate"/>
10       <property name="hibernate.show_sql" value="true"/>
11       <property name="hibernate.hbm2ddl.auto" value="update"/>
12     </properties>
13   </persistence-unit>
14 </persistence>

其实这个hibernate.hbm2ddl.auto参数的作用主要用于:自动创建|更新|验证数据库表结构。如果不是此方面的需求建议set value="none"。里面可以设置的几个参数:

validate 每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

create 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。

create-drop 每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。

update 最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。

注意:请慎重使用此参数,没必要就不要随便用。如果发现数据库表丢失,请检查hibernate.hbm2ddl.auto的配置。

通常在企业开发中,有两种做法:

  1. 先建表,后再根据表来编写配置文件和实体bean。使用这种方案的开发人员受到了传统数据库建模的影响。
  2. 先编写配置文件和实体bean,然后再生成表,使用这种方案的开发人员采用的是领域建模思想,这种思想相对前一种思想更加OOP。


建议使用第二种(领域建模思想),从软件开发来想,这种思想比第一种思想更加面向对象。 领域建模思想也是目前比较新的一门建模思想,第一种是传统的建模思想,已经有10来年的发展历程了,而领域建模思想是近几年才兴起的,这种思想更加的面向对象。




posted @ 2011-11-28 23:44  一直在等  阅读(3831)  评论(1编辑  收藏  举报