搭建spring+hibernate+springmvc

web.xml配置java

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!-- 配置spring的配置文件的位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <!-- 配置spring隨web容器啓動時就建立 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--configure the setting of springmvcDispatcherServlet and configure the mapping-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
        </init-param>
        <!-- <load-on-startup>1</load-on-startup> -->
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

springmvc-servlet.xmlmysql

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

       <!-- scan the package and the sub package -->
       <context:component-scan base-package="com.chen"/>

       <!-- don't handle the static resource -->
       <mvc:default-servlet-handler />

       <!-- if you use annotation you must configure following setting -->
       <mvc:annotation-driven />

       <!-- configure the InternalResourceViewResolver -->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
             id="internalResourceViewResolver">
              <!-- 前綴 -->
              <property name="prefix" value="/WEB-INF/view/" />
              <!-- 後綴 -->
              <property name="suffix" value=".jsp" />
       </bean>
</beans>

applicationContext.xml配置web

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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-3.0.xsd">

       <!--  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> -->
       <!--      <property name="location"> -->
       <!--       <value>/WEB-INF/config.properties</value> -->
       <!--    </property> -->
       <!--  </bean>  -->
       <!-- 配置數據源 -->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <!-- 配置數據庫鏈接基本信息 -->
              <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
               <!--- datetime 時間不轉換 ----->
              <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/spider?noDatetimeStringSync=true" />
              <property name="user" value="root" />
              <property name="password" value="root" />

              <!-- 配置初始化大小、最小、最大 -->
              <property name="initialPoolSize" value="3" />
              <property name="maxPoolSize" value="20" />
              <property name="minPoolSize" value="1" />
              <!-- 配置獲取鏈接等待超時的時間 -->
              <property name="maxIdleTime" value="60000" />
       </bean>
       <!-- 組件自動掃描&&注入 -->
       <!-- 使用 annotation -->
       <!--<context:annotation-config />-->

       <!-- 使用 annotation 自動註冊bean -->
       <!--<context:component-scan base-package="src.main.java.com.star.*" />-->
       <!-- 配置session工廠 -->
       <bean id="sessionFactory"
             class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
              <property name="dataSource" ref="dataSource" />
              <property name="hibernateProperties">
                     <props>
                            <prop key="hibernate.hbm2ddl.auto">update</prop>
                            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                            <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
                            <prop key="hibernate.show_sql">true</prop>
                     </props>
              </property>
              <property name="mappingLocations">
                  <value>classpath:mappers/*.hbm.xml</value>
              </property>
       </bean>
       <!--  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -->
       <!--   <property name="dataSource" ref="dataSource"/> -->
       <!--   <property name="hibernateProperties"> -->
       <!--    <value> -->
       <!--    hibernate.dialect=org.hibernate.dialect.MySQLDialect -->
       <!--    hibernate.show_sql=true -->
       <!--    hibernate.format_sql=false -->
       <!--    hibernate.query.substitutions=true 1, false 0 -->
       <!--    hibernate.jdbc.batch_size=20 -->
       <!--    hibernate.query.factory_class=org.hibernate.hql.classic.ClassicQueryTranslatorFactory -->
       <!--    </value> -->
       <!--   </property> -->
       <!--  </bean> -->

       <!-- 數據源事務管理 -->
       <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource" />
       </bean>

       <!-- 注入sessionFactory -->
       <!--<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">-->
              <!--<property name="sessionFactory" ref="sessionFactory" />-->
       <!--</bean>-->
</beans>

 

pom.xml的依賴spring

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ssh</groupId>
    <artifactId>ssh</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.1.RELEASE</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.1.RELEASE</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.1.6.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

    </dependencies>

</project>

基於xml配置sql

mappers/Action.hbm.xml數據庫

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/xsd/hibernate-mapping/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.chen.bean">
    <class name="com.chen.bean.Action" table="tbl_action">
        <id column="id" name="id"/>
        <property name="create_time" />
        <property name="name" />
        <property name="log" />
        <property name="update_time" />
        <property name="status" />
    </class>
</hibernate-mapping>

bean文件apache

package com.chen.bean;

public class Action {
    private int id;
    private String create_time;
    private String name;
    private String log;
    private String status="2";
    private String update_time;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCreate_time() {
        return create_time;
    }

    public void setCreate_time(String create_time) {
        this.create_time = create_time;
    }

    public String getName() {
        return name;
    }

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

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getUpdate_time() {
        return update_time;
    }

    public void setUpdate_time(String update_time) {
        this.update_time = update_time;
    }

    @Override
    public String toString() {
        return "Action{" +
                "id=" + id +
                ", create_time='" + create_time + '\'' +
                ", name='" + name + '\'' +
                ", log='" + log + '\'' +
                ", status='" + status + '\'' +
                ", update_time='" + update_time + '\'' +
                '}';
    }
}

dao文件spring-mvc

package com.chen.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.chen.bean.Action;

import java.util.List;

@Repository
public class ActionDao {

    private Session session;

    @Autowired
    private void setSession(SessionFactory factory){
        session = factory.getCurrentSession();
    }


    public List<com.chen.bean.Action> getActions(){
        return session.createQuery(" from "+  com.chen.bean.Action.class.getName() + " a  where a.id >1").list();
    }

    public Action save(Action a){
        session.clear();
        session.save(a);
        session.flush();
        return  a;
    }

}

controller調用session

package com.chen;

import com.chen.dao.ActionDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.chen.bean.Action;
@RestController
@RequestMapping("/Index")
public class IndexController {

    @RequestMapping("/index")
    public String index(){

        Action a = new Action();
        a.setName("action_h"+System.currentTimeMillis());
        a.setLog("action_h");
        a.setCreate_time("2017-9-17");
        a.setUpdate_time("2017-9-18");
        System.out.println(dao.save(a).toString());
        return dao.getActions().toString();
    }


    @Autowired
    ActionDao dao;
}

註解方式mvc

applicationContext.xml中 的sessionFactory修改

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="hibernateProperties">
        <props>
            <!--<prop key="hibernate.hbm2ddl.auto">none</prop>-->
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
    <!-- xml配置 -->
    <!--<property name="mappingLocations">-->
        <!--<value>classpath:mappers/*.hbm.xml</value>-->
    <!--</property>-->

    <!-- 註解 -->
    <property name="packagesToScan">
        <value>com.chen.*</value>
    </property>
</bean>

bean配置

package com.chen.bean;

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

@Entity
@Table(name = "tbl_action")
public class Action {
    @Id
    @GenericGenerator(name = "generator", strategy = "increment")
    @Column(name = "id")
    @GeneratedValue(generator = "generator")
    private int id;
    @Column
    private String create_time;
    @Column(name = "name",length = 255)
    private String name;
    @Column
    private String log;
    @Column
    private String status="2";
    @Column
    private String update_time;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCreate_time() {
        return create_time;
    }

    public void setCreate_time(String create_time) {
        this.create_time = create_time;
    }

    public String getName() {
        return name;
    }

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

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getUpdate_time() {
        return update_time;
    }

    public void setUpdate_time(String update_time) {
        this.update_time = update_time;
    }

    @Override
    public String toString() {
        return "Action{" +
                "id=" + id +
                ", create_time='" + create_time + '\'' +
                ", name='" + name + '\'' +
                ", log='" + log + '\'' +
                ", status='" + status + '\'' +
                ", update_time='" + update_time + '\'' +
                '}';
    }
}
相關文章
相關標籤/搜索