自己扩展封装Hibernate模板DAO-之二单独使用(hibernate)

 1.引入Hibernate3.6的jar包及必须依赖包及JPA包

2.引入haha.hibernate.jar 及commons-beanutils-1.8.3.jar,commons-lang-2.5.jar三个包,我已发布了http://download.csdn.net/user/Lijun7788

3.引入数据库驱动包

自己扩展封装Hibernate模板DAO-之二单独使用(hibernate)_第1张图片

我这里选择了一个非常简单的表

UserRoles (id int ,name String)来做个测试,采用注解的方式

UserRoles.java文件如下:

package com.haha.bean;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class UserRoles implements Serializable {
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private int id;
	private String name;
	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.cfg.xml文件如下

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<property name="myeclipse.connection.profile">sql</property>
	<property name="connection.url">
		jdbc:sqlserver://127.0.0.1:1433;databaseName=mybookshop
	</property>
	<property name="connection.username">sa</property>
	<property name="connection.password"></property>
	<property name="connection.driver_class">
		com.microsoft.sqlserver.jdbc.SQLServerDriver
	</property>
	<property name="dialect">
		org.hibernate.dialect.SQLServerDialect
	</property>
	<property name="show_sql">true</property>
	<mapping class="com.haha.bean.UserRoles" />
</session-factory>

</hibernate-configuration>

UserRoleDao.java文件:

package com.haha.dao;

import java.util.List;

import com.haha.bean.UserRoles;
import com.haha.hibernate.HibernateDao;

public class UserRoleDao extends HibernateDao<UserRoles, Integer> {
	public List<UserRoles> findAll(){
		return getAll("id",true);
	}
	
	public void add(UserRoles role){
		save(role);
	}
}

UserRoleTest.java文件:

package com.haha.test;

import java.util.List;

import com.haha.bean.UserRoles;
import com.haha.dao.UserRoleDao;

public class UserRoleTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		addTest();
		findAllTest();
	}

	private static void findAllTest() {
		List<UserRoles> list=new UserRoleDao().findAll();
		for(UserRoles r:list)
			System.out.println(r.getId()+"."+r.getName());
		
	}

	private static void addTest() {
		UserRoles role=new UserRoles();
		role.setName("经理");
		new UserRoleDao().add(role);		
		
	}

}

运行结果:



非常的简单

 

 

你可能感兴趣的:(Hibernate,String,MyEclipse,Class,sqlserver,扩展)