hibernate 的基本用法

1 hibernate 的myeclipse的快速搭建方法

点击项目-》configure-》configure facets -》install hibernate facet

2 配置Hibernate.cfg.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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

	<session-factory>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/students
		</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.username">root</property>
		<property name="connection.password">123</property>
		<mapping resource="student.hbm.xml"></mapping>
	</session-factory>

</hibernate-configuration>

也可以利用下面的可视化配置方式

cfg.xml中需要导入hbm.xml的文件,而hbm.xml的配置需要根据持久化类进行配置

因此先编写持久化类,然后编写hbm.xml文件

package com.test;

public class student {
	String id;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	String name;
	String password;
	String adress;
	String phonenum;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getAdress() {
		return adress;
	}
	public void setAdress(String adress) {
		this.adress = adress;
	}
	public String getPhonenum() {
		return phonenum;
	}
	public void setPhonenum(String phonenum) {
		this.phonenum = phonenum;
	}
}

然后配置hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.test.student">
		<id name="id" column="id">
			<generator class="native"></generator>
		</id>
		
		<property name="name" column="sname"></property>
		<property name="adress" column="adress"></property>
		<property name="password"></property>
		<property name="phonenum" column="phone"></property>
	</class>
</hibernate-mapping>

最后加入测试类

package com.test;



import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration config=new Configuration().configure();
		SessionFactory sfa=config.buildSessionFactory();
		Session se=sfa.openSession();
		Transaction tra =se.beginTransaction();
		student stu=new student();
		stu.setId("3");
		stu.setAdress("宁波");
		stu.setName("liu");
		stu.setPhonenum("15658953322");
		stu.setPassword("12545");
		se.save(stu);
		tra.commit();
		se.close();
		sfa.close();

	}

}

关于bibernate增删改查在下一篇博文

猜你喜欢

转载自blog.csdn.net/zhunquanjiong6199/article/details/82147812
今日推荐