数据插入hibernate(dao分层)

bean1.java

package bean;

public class bean1 {
String name="123123";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "bean1 [name=" + name + "]";
}

}

bean2.java

package bean;

public class bean2 {
    String name="0";
    int id=1;
public void setBean1(bean1 bean1){
    System.out.println(bean1);
    this.name=bean1.getName();
}
public void setName(String name) {
    this.name = name;
}
public String getName() {
    return name;
}
public void setId(int id) {
    this.id = id;
}
public int getId() {
    return id;
}
@Override
public String toString() {
    return "bean2 [name=" + name + "]";
}

}

WebDao.java

package dao;

import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import bean.bean2;

public class WebDao extends HibernateDaoSupport {
    
    public  WebDao() {
        System.out.println("dao");
    }
    
    public void save(bean2 bean2) {
        System.out.println(bean2);
        HibernateTemplate hibernateTemplate=  this.getHibernateTemplate();
        System.out.println("hibernateTemplate:"+hibernateTemplate);
        getHibernateTemplate().setCheckWriteOperations(false);
       this.getHibernateTemplate().save(bean2);    
       getHibernateTemplate().flush();
       System.out.println("保存成功!");
       
    }
    
    public final void setMySessionFactory(SessionFactory sf) {
        
    }

}

bean2.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
   <!-- 配置表与实体对象的关系 -->
   <!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
<hibernate-mapping package="bean" >
    <!-- 
        class元素: 配置实体与表的对应关系的
            name: 完整类名
            table:数据库表名
     -->
    <class name="bean2" table="test_bean" >
        
        <id name="id"  >
            <generator class="native"></generator>
        </id>
        <property name="name"  >
            </property>
        
        
    </class>
</hibernate-mapping>

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>

<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>

        <property name="hibernateProperties">
            <props>
                <!--  必选配置 -->
                <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.url" >jdbc:mysql:///test</prop>
                <prop key="hibernate.connection.username" >root</prop>
                <prop key="hibernate.connection.password" >root</prop> 
                
                <!--  可选配置 -->
                <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql" >true</prop>
                <prop key="hibernate.format_sql" >true</prop>
                <prop key="hibernate.hbm2ddl.auto" >update</prop>
            </props>
        </property>
        <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
        <property name="mappingDirectoryLocations" value="classpath:" ></property> 
        
        
    </bean>
    
<bean name="bean1" class="bean.bean1"></bean>
    <bean name="bean2" class="bean.bean2">
    <property name="bean1" ref="bean1"></property>
    </bean>
    <bean name="beanDao" class="dao.WebDao">
    <property name="sessionFactory" ref ="sessionFactory">
</property></bean>
    
</beans>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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>
    
        <!-- 
        #hibernate.dialect org.hibernate.dialect.MySQLDialect
        #hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
        #hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
        #hibernate.connection.driver_class com.mysql.jdbc.Driver
        #hibernate.connection.url jdbc:mysql:///test
        #hibernate.connection.username gavin
        #hibernate.connection.password
         -->
         <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///test</property>
         <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
         <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">root</property>
        <!-- 数据库方言
            不同的数据库中,sql语法略有区别. 指定方言可以让hibernate框架在生成sql语句时.针对数据库的方言生成.
            sql99标准: DDL 定义语言  库表的增删改查
                      DCL 控制语言  事务 权限
                      DML 操纵语言  增删改查
            注意: MYSQL在选择方言时,请选择最短的方言.
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        
        <!-- #hibernate.show_sql true 
             #hibernate.format_sql true
        -->
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
        <property name="hibernate.format_sql">true</property>
        <!-- 
        ## auto schema export  自动导出表结构. 自动建表
        #hibernate.hbm2ddl.auto create        自动建表.每次框架运行都会创建新的表.以前表将会被覆盖,表数据会丢失.(开发环境中测试使用)
        #hibernate.hbm2ddl.auto create-drop 自动建表.每次框架运行结束都会将所有表删除.(开发环境中测试使用)
        #hibernate.hbm2ddl.auto update(推荐使用) 自动生成表.如果已经存在不会再生成.如果表有变动.自动更新表(不会删除任何数据).
        #hibernate.hbm2ddl.auto validate    校验.不自动生成表.每次启动会校验数据库中表是否正确.校验失败.
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
    
        
        <mapping resource="bean2.hbm.xml"></mapping>
        
    </session-factory>
</hibernate-configuration>

TempTest.java

package art_test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import bean.bean2;
import dao.WebDao;

public class TempTest {

public void testSessionFactory(){
    ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext-dao.xml");
//    System.out.println("ac:"+ac);
    Object bean=ac.getBean("sessionFactory");
    System.out.println("bean:"+bean);
}

public void testBean(){
    ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//    System.out.println("ac:"+ac);
    bean2 bean2=(bean2) ac.getBean("bean2");
    System.out.println("bean2:"+bean2);
    bean2.setName("test");
    
//    WebDao beandao=new WebDao();
//    ClassPathXmlApplicationContext resource = new ClassPathXmlApplicationContext("applicationContext.xml");
    WebDao dao=(WebDao) ac.getBean("beanDao");
    System.out.println(".........");
    dao.save(bean2);
}

public static void main(String[] args) {
    TempTest tempTest=new TempTest();
    tempTest.testBean();
}
}

总结:

1 要自己先在mysql数据库中建表

2 表的标签id是主键,property是普通属性

3 dao要自动注入,不能使用new创建

4 applicationcontext.xml中通过<property name="mappingDirectoryLocations" value="classpath:" ></property> 来引入hibernate.cfg.xml通过<mapping resource="bean2.hbm.xml"></mapping>来建立数据库映射

猜你喜欢

转载自www.cnblogs.com/withbear/p/11837738.html