Hibernat4.3.5+JPA

所需JAR包:

antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.4.Final.jar
hibernate-core-4.3.5.Final.jar
hibernate-entitymanager-4.3.5.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-jpamodelgen-4.3.5.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
mysql-connector-java-5.0.0-beta-bin.jar

项目下载地址


实体类
@Entity(name="student")
public class User{

private int id;

private String name;


@Id
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;
}
}


hibernate配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC连接设置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 连接池配置,使用c3p0连接池 -->
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!-- 数据库语言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- sql设置 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 持久类设置所有需要持久的类要在这里标明,以下是针对annotation注释的类 -->
<mapping class="hibernate.entity.User" />
</session-factory>
</hibernate-configuration>

工具类
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();


private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}


public static SessionFactory getSessionFactory() {
return sessionFactory;
}


}

测试类


public class UserTest01{

@Test
public void save(){
Configuration configuration=new Configuration();
configuration.configure();
SessionFactory sessionFactory=configuration.buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
User user=new User();
user.setName("1");
session.save(user);
transaction.commit(); 
session.close();
}
}






你可能感兴趣的:(Hibernate,c3p0,连接池,jpa,单元测试)