Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

SSH series: (3) Hibernate

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

(1)引入jar包

(2)配置

(3)测试

1、引入jar包

引入mysql jar包

mysql-connector-java-5.1.38-bin.jar

引入c3p0 jar包

c3p0-0.9.1.2.jar

引入hibernate相关jar包 (hibernate-distribution-3.6.0.Final)

antlr-2.7.6.jar

commons-collections-3.1.jar

dom4j-1.6.1.jar

hibernate3.jar

hibernate-jpa-2.0-api-1.0.0.Final.jar

javassist-3.12.0.GA.jar

jta-1.1.jar

slf4j-api-1.6.1.jar

2、配置

2.1、添加实体类:Person.java

package com.rk.test.entity;/** * 实体层Person类 DTO * * */public class Person { private String pId; private String pName; private int pVersion; public String getpId() { return pId; } public void setpId(String pId) { this.pId = pId; } public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public int getpVersion() { return pVersion; } public void setpVersion(int pVersion) { this.pVersion = pVersion; } @Override public String toString() { return "Person [pId=" + pId + ", pName=" + pName + ", pVersion=" + pVersion + "]"; } }

2.2、添加映射文件:Person.hbm.xml

2.3、添加Hibernate配置文件:hibernate.cfg.xml

com.mysql.jdbc.Driver jdbc:mysql:///tax_sys root root org.hibernate.dialect.MySQL5Dialect true false update thread

3、测试

测试两方面:第一是能从数据库读取一条数据,第二是能向数据库保存一条数据

package com.rk.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.junit.Before;import org.junit.Test;import com.rk.test.entity.Person;public class TestHibernate { private SessionFactory sf; @Before public void init() { sf = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); } @Test public void test() { Session session = sf.getCurrentSession(); session.beginTransaction(); Person p = (Person) session.get(Person.class, "4028d081564a762001564a76221e0000"); System.out.println(p); Person p2 = new Person(); p2.setpName("Tomcat"); session.save(p2); session.getTransaction().commit(); }}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report