Hibernate JPA注解入门

1 实体类

/**
 * 客户
 * @author http://www.yiidian.com
 */
@Entity
@Table(name = "t_customer")
public class Customer {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private Integer id;
	@Column(name = "name")
	private String name;
	@Column(name = "gender")
	private String gender;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

}

@Entity

声明一个类为实体Bean。

@Table

说明此实体类映射的表名,目录,schema的名字。

@Id

声明此表的主键。

@GeneratedValue

定义主键的增长策略。我这里一般交给底层数据库处理,所以调用了名叫generator的增长方式,由下边的@GenericGenerator实现

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">
	
<hibernate-configuration>	
	<!-- 连接数据库的参数 -->
<session-factory>
	<!-- 1.连接数据库参数 -->
	<property name="hibernate.connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="hibernate.connection.url">
		jdbc:mysql://localhost:3306/hibernate
	</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">root</property>

	<!-- 整合c3p0 -->
	<property name="hibernate.connection.provider_class">
		org.hibernate.c3p0.internal.C3P0ConnectionProvider
	</property>
	<!-- c3p0详细配置 -->
	<property name="c3p0.min_size">10</property>
	<property name="c3p0.max_size">20</property>

	<!-- hibernate方言 -->
	<property name="hibernate.dialect">
		org.hibernate.dialect.MySQLDialect
	</property>

	<!-- 2.hibernate扩展参数 -->
	<property name="hibernate.show_sql">true</property>
	<property name="hibernate.format_sql">true</property>
	<property name="hibernate.hbm2ddl.auto">update</property>

	<!-- 让session被TheadLocal管理 -->
	<property name="hibernate.current_session_context_class">
		thread
	</property>
	<property name="dialect"></property>

	<mapping class="com.yiidian.domain.Customer" />

</session-factory>
</hibernate-configuration>	

注意:查找映射实体类使用

<mapping class="com.yiidian.domain.Customer" />

3 编写测试类

/**
 * 演示JPA的入门开发
 * @author lenovo
 *
 */
public class Demo {

	@Test
	public void test1(){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		
		Customer cust = new Customer();
		cust.setName("王五");
		cust.setGender("男");
		session.save(cust);
		
		tx.commit();
	}
	
}

控制台结果:

Hibernate: 
    insert 
    into
        t_customer
        (gender, name) 
    values
        (?, ?)

 

源码下载:https://pan.baidu.com/s/1miqYUMk

热门文章

优秀文章