hiberate单独开发的基本配置

来源:互联网 发布:监控linux下tomcat 编辑:程序博客网 时间:2024/05/22 04:31

目录结构:
-src
    -test..java
    -User.java
-hibernate.cfg.xml
-User.hbm.xml

User.java:

public class User {
    private int id;
    private String username;
    private String password; 

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

test.java:

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class test {

 public static void main(String[] args) {

  try {
   SessionFactory sf = new Configuration().configure()
     .buildSessionFactory();
   Session session = sf.openSession();
   Transaction tx = session.beginTransaction();

   User user = new User();
   user.setUsername("Blog");
   //user.setPassword("分享java快乐");

   session.delete(user);
   tx.commit();
   session.close();

  } catch (HibernateException e) {
   e.printStackTrace();
  }
 }
}
User.hbm.xml
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
 
<hibernate-mapping>

    <class name="User" table="UserTable">
        <id name="id">
            <generator class="assigned" />
        </id>
        <property name="username"  />
        <property name="password" />  
    </class>

</hibernate-mapping>

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">mysql</property>
 <property name="connection.url">
  jdbc:mysql://127.0.0.1:3306/test
 </property>
 <property name="connection.username">root</property>
 <property name="connection.password"></property>
 <property name="connection.driver_class">
  com.mysql.jdbc.Driver
 </property>
 <property name="dialect">
  org.hibernate.dialect.MySQLDialect
 </property>
 <mapping resource="User.hbm.xml"/>
</session-factory>

</hibernate-configuration>

原创粉丝点击