第一个简单的hibernate小例子


一直在用mybatis.因为要写很多表的联合查询语句。

听很多人说起hibernate。说是封装的如何好之类。

于是想学习一下。

网上搜的例子在我这各种报错:log4j的,Configuring ehcache from ehcache-failsafe.xml 等。

最后费了老劲终于让程序走通-----还是hibernate jar包的问题。


于是决定把做的程序呈现出来,最重要的是把jar包提供给跟我一样被各种下载坑出翔的人。


1.建立java项目。

2.引入jar包----hibernate核心包和oracle驱动包。

关于oracle驱动包:我的jdk是1.6,我引用ojdbc5.jar或者ojdbc6.jar 都可以。(有人说如果jdk是1.5,那么不能用ojdbc6.jar,我没试过,不知道真假。)  如果你的机器安装了oracle,那么oracle驱动在这个目录下:D:\app\Administrator\product\11.2.0\dbhome_1\jdbc\lib。

hibernate包下载.点击打开链接.  oracle驱动下载点击打开链接

3.本项目用的数据库是oracle.  用到的表是 user1

create table USER1
(
  ID       VARCHAR2(110),
  USERNAME VARCHAR2(11),
  PASSWORD VARCHAR2(11)
)



一。程序目录:


  

1.建立User类。

package d;


public class User {
	 private String id;
   private String username;
   private String password;
public String getUsername() {
	return username;
}
public void setUsername(String username) {
	this.username = username;
}
public String getPassword() {
	return password;
}
public void setPassword(String password) {
	this.password = password;
}
public String getId() {
	return id;
}
public void setId(String id) {
	this.id = id;
}
}

2.在package d下建立User.hbm.xml 。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
	
<hibernate-mapping>
	<class name="d.User" table="user1">
		<id name="id" >
			<generator class="uuid"/>
		</id>
		<property name="username"/>
		<property name="password"/>
		
	</class>
</hibernate-mapping>

3. 配置hibernate.cfg.xml文件

<pre name="code" class="html"><!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
<!--程序执行的时候是否显示真正的sql语句-->
  <property name="show_sql">true</property>
  <!--使用的SQL对应的“方言”,此处是Oracle9的“方言”-->
<property name="dialect">org.hibernate.dialect.Oracle9Dialect
</property>
  <!--连接数据库的Driver-->
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
  <!--数据库连接url-->
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:orcl
</property>
  <!--用户名-->
<property name="connection.username">system</property>
<!--密码-->
  <property name="connection.password">manager</property>
<mapping resource="d/User.hbm.xml"/>
 </session-factory>
</hibernate-configuration>


 

4.在src目录下建立log4j.properties

如果缺少log4j.properties ,会引起警告

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).log4j:WARN Please initialize the log4j system properly.

log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

5.建立ehcache.xml 文件。

如果缺少ehcache.xml ,会引起警告

 WARN [net.sf.ehcache.config.Configurator] - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Users/Administrator/Desktop/hibjar/ehcache-1.1.jar!/ehcache-failsafe.xml


<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required:

        maxElementsInMemory            - Sets the maximum number of objects that will be created in memory
        eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the
                                         element is never expired.
        overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
                                         has reached the maxInMemory limit.

        The following attributes are optional:
        timeToIdleSeconds              - Sets the time to idle for an element before it expires.
                                         i.e. The maximum amount of time between accesses before an element expires
                                         Is only used if the element is not eternal.
                                         Optional attribute. A value of 0 means that an Element can idle for infinity.
                                         The default value is 0.
        timeToLiveSeconds              - Sets the time to live for an element before it expires.
                                         i.e. The maximum time between creation time and when an element expires.
                                         Is only used if the element is not eternal.
                                         Optional attribute. A value of 0 means that and Element can live for infinity.
                                         The default value is 0.
        diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
                                         The default value is false.
        diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
                                         is 120 seconds.
        -->

    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
        />
</ehcache>



6.建立Client类。尝试保存数据。

package d;

import java.util.Date;

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

public class Client {
	public static void main(String[] args) {
		//读取配置文件
		Configuration cfg = new Configuration().configure();
		
		SessionFactory factory = cfg.buildSessionFactory();
		
		Session session = null;
		try{
			session = factory.openSession();
			//开启事务
			session.beginTransaction();
			
			User user = new User();
			user.setUsername("用户名");
			user.setPassword("123");
		
			session.save(user);
			//提交事务
			session.getTransaction().commit();
			
		}catch(Exception e){
			e.printStackTrace();
			//回滚事务
			session.getTransaction().rollback();
		}finally{
			if(session != null){
				if(session.isOpen()){
					//关闭session
					session.close();
				}
			}
		}
	}
}


运行Client 为java application 。

控制台出现Hibernate: insert into user1 (username, password, id) values (?, ?, ?)。表示插入了一条语句。


该文章参考了http://blog.csdn.net/aboy123/article/details/10085635   

新手上路之Hibernate:第一个Hibernate例子






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITSDSDFSDF

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值