hibernate 开发步骤

1 创建Customer表
CREATE TABLE CUSTOMER 
(
 CID int NOT NULL PRIMARY KEY ,
 USERNAME varchar(20)  ,
 PASSWORD varchar(20)
)

2 创建Customer表对应的Java类POJO
package hibtest;

public class Customer 
{
 private int id;
    private String username;
    private String password;
    
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 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;
 }
    
    
}

3 配置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">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
        <property name="connection.url">jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=WebDB</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">jsj</property>

        <property name="connection.pool_size">2</property>
        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="show_sql">true</property>

        <mapping resource="Customer.hbm.xml"/>
       
    </session-factory>
</hibernate-configuration>

4 创建Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        '-//Hibernate/Hibernate Mapping DTD 3.0//EN'
        'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>
<hibernate-mapping>
    <class name="testhi.Customer" table="CUSTOMER">
        <id name="id" column="CID">
            <generator class="assigned"/>
        </id>
       <property name="username" column="USERNAME" />
        <property name="password" column="PASSWORD" />
    </class>
</hibernate-mapping>

5 编写测试程序
SessionFactory sf =   new Configuration().configure().buildSessionFactory();
            //Configuration cfg = new Configuration().configure();
            //cfg.addURL(Test.class.getResource("/Customer.hbm2.xml"));
            //SessionFactory sf = cfg.buildSessionFactory();


            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();

            for (int i = 0; i < 200; i++) {
                Customer customer = new Customer();
                customer.setId(i);
                customer.setUsername("customer" + i);
                customer.setPassword("customer");
                session.save(customer);
            }
 tx.commit();
            session.close();



 

  

Top
收藏
关注
评论
原文地址:https://www.cnblogs.com/alanjl/p/3378162.html