文章目录

写在前面

今天学习了Hibernate操作数据库的步骤,特写此笔记巩固学习成果,加深记忆。

  • 首先

在数据库中创建表,写好Pojo类,用:

@Entity
@Table(name="students")

创建好映射,并配置好hibernate.cfg.xml:

<mapping class="com.core.dao.pojo.StudentsPojo"/>

然后就可以新建测试类,在主方法中进行下面步骤测试:

  • 获得数据库连接

Session s=HibernateSessionFactory.getSession();
  • 创建事务

Transaction tr=s.beginTransaction();
  • 创建表对应的Pojo类

StudentsPojo st = new StudentsPojo();
  • 将数据装入Pojo类

st.setSname("代码L");
st.setSex("¥¥¥");
st.setAddress("火星");
st.setPassword("666");
  • 将Pojo类对象提交到数据库

s.save(st);//提交到数据库
tr.commit();//事务提交
  • 关闭数据库连接

s.close();

附上hibernate.cfg.xml 全部代码:

<!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>
	<property name="dialect">
		org.hibernate.dialect.MySQL5InnoDBDialect
	</property>
	<!-- jdbc:mysql://115.29.106.17:3306/prdfdb?useUnicode=true&amp;characterEncoding=UTF-8 -->
	<property name="connection.url">jdbc:mysql://localhost:3307/swcj?useUnicode=true&amp;characterEncoding=UTF-8
	</property>
	<property name="connection.username">root</property>
	<property name="connection.password">123456</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="show_sql">true</property>
	<property name="transaction.factory_class">
		org.hibernate.transaction.JDBCTransactionFactory
	</property>
	<property name="hibernate.connection.provider_class">
		org.hibernate.connection.C3P0ConnectionProvider
	</property>
	<!--连接池的最小连接数-->
	<property name="hibernate.c3p0.min_size">5</property>
	<!--最大连接数-->
	<property name="hibernate.c3p0.max_size">10</property>
	<!--连接超时时间-->
	<property name="hibernate.c3p0.timeout">1800</property>
	<!--statemnets缓存大小-->
	<property name="hibernate.c3p0.max_statements">5</property>
	<!--每隔多少秒检测连接是否可正常使用  -->
	<property name="hibernate.c3p0.idle_test_period">121</property>
	<!--当池中的连接耗尽的时候一次性增加的连接数量,默认为3-->
	<property name="hibernate.c3p0.acquire_increment">3</property>
	<property name="hibernate.c3p0.validate">true</property>
	<property name="javax.persistence.validation.mode">none</property>
	
	<mapping class="com.core.dao.pojo.StudentsPojo"/>
        
    </session-factory>
</hibernate-configuration>

后记:现在好好学Java,毕业设计不用愁,加油!