hibernate基礎簡單入門1---helloword

來源:互聯網
上載者:User

標籤:creat   user   begin   apply   conf   turn   more   uil   doctype   

1:目錄結果

2:實體類(student.java)

package com.www.entity;public class Student {private int id;private String    name;private int age;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;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;}}

3:實體類映射表(Student.hbm.xml)

<!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping>    <class name="com.www.entity.Student" table="stu_tab2">        <id name="id" column="stu_id">            <generator class="native"></generator>        </id>        <property name="name" column="stu_name"></property>        <property name="age" column="stu_age"></property>    </class></hibernate-mapping>

4:hibernate設定檔(hibernate.cfg.xml)

<!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>    <!--配置mysql資料庫連接參數-->    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql:///hibernate</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password"></property><mapping resource="com/www/entity/Student.hbm.xml"/></session-factory></hibernate-configuration>

5:記錄檔(log4j.properties)

log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ###log4j.rootLogger=warn, stdout#log4j.logger.org.hibernate=infolog4j.logger.org.hibernate=debuglog4j.logger.org.hibernate.type=info### log schema export/update ###log4j.logger.org.hibernate.tool.hbm2ddl=debug

6:單元測試檔案(StudentTest.java)

package com.www.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.tool.hbm2ddl.SchemaExport;import org.junit.Test;import com.www.entity.Student;public class StudentTest {    // 1.自動建立資料庫表,不用建立表,它能自動幫你建立表。    @Test    public void createTable() {        Configuration configuration = new Configuration().configure();        SchemaExport se = new SchemaExport(configuration);        se.create(true, true);    }    //添加    @Test    public void add() {        Configuration cfg = new Configuration().configure();        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());        ServiceRegistry service = ssrb.build();        SessionFactory factory = cfg.buildSessionFactory(service);        Session session = factory.openSession();        Transaction tx = session.beginTransaction();        Student stu = new Student();        stu.setAge(20);        stu.setName("wowo");        try {            session.save(stu);            tx.commit();        } catch (Exception e) {            // TODO: handle exception            tx.rollback();        } finally {            session.close();        }    }    //查看@Test    public void get() {        Configuration cfg = new Configuration().configure();        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());        ServiceRegistry service = ssrb.build();        SessionFactory factory = cfg.buildSessionFactory(service);        Session session = factory.openSession();        Transaction tx = session.beginTransaction();        try {            Student stu = (Student) session.get(Student.class, 1);            System.out.println(stu.getId() + stu.getName() + stu.getAge());            tx.commit();        } catch (Exception e) {            // TODO: handle exception            tx.rollback();        } finally {            session.close();        }    }}

7:另一種hibernate串連資料庫的設定檔(hibernate.properties)

目錄結構:

hibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://localhost:3306/hibernatehibernate.connection.username=roothibernate.connection.password=hibernate.show_sql=true

 

總結:hibernate建立基本都是這六步,下面的記死

Configuration cfg = new Configuration().configure();        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());        ServiceRegistry service = ssrb.build();        SessionFactory factory = cfg.buildSessionFactory(service);        Session session = factory.openSession();        Transaction tx = session.beginTransaction();

 

hibernate基礎簡單入門1---helloword

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.