Spring与Hibernate整合入门实例



Spring、SpringMVC、Hibernate的整合
Spring框架搭建

添加依赖:

<!-- spring-framework -->
    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>4.3.2.RELEASE</version>
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-beans</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>  

    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-webmvc</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>  

    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-orm</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>  
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-websocket</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>  
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-oxm</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-test</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-core</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency> 
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-aop</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency> 
    
    <dependency>  
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-beans</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-jdbc</artifactId>  
        <version>4.3.2.RELEASE</version>
    </dependency> 
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-expression</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-aspects</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-instrument</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>

    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-jms</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-messaging</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>
    
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-tx</artifactId>  
        <version>4.3.2.RELEASE</version>  
    </dependency>

我把几乎所有关于Spring Framework的依赖都添加了进来,方便以后扩展。

然后添加hibernate依赖:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

mysql与Java的连接工具:

      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.9</version>
      </dependency>

JAVA对象转换为JSON数据的工具:

      <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
          <version>1.9.13</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.6.1</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.6.1</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.6.1</version>
      </dependency>
      <dependency>
          <groupId>org.json</groupId>
          <artifactId>json</artifactId>
          <version>20140107</version>
      </dependency>

先配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
                    id="WebApp_ID" 
                    version="3.0">
  <display-name>spring-ok</display-name>
  <welcome-file-list>
    <welcome-file>test.html</welcome-file>
  </welcome-file-list>
  <context-param>
        <param-name>applicationContext</param-name>
        <param-value>
        classpath:applicationContext.xml
        </param-value>
  </context-param>
  <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
  </listener>
  <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
  </listener>
  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
  </servlet>
  
  <!-- Spring MVC处理的URL -->
  <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>

标签解释:

display-name:servlet的名字

welcome-file-list:首页列表

context-param:spring容器相关,classpath是spring的bean配置文件的名字,而这个文件最好和web.xml放在同一目录。

listener:监听器,用于监听各种web事件。

servlet:服务程序连接器,用来处理请求和发送响应。如果servlet-name是spring,那么对应的servlet配置文件就是spring-servlet.xml,要放在和web.xml同一目录下。load-on-startup表示启动web后启动servlet的时机,如果是正数,就在启动web后立即启动,并且正数越小,越先启动。

servlet-mapping:用来指定访问路径,有几种选择:*.do;*.action;/*等等。

spring-servlet.xml文件建立好先不需要配置。

下面是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:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="cn.jdfo.dao"/>
    <context:component-scan base-package="cn.jdfo.service"/>
    <context:component-scan base-package="cn.jdfo.web"/>
    <mvc:annotation-driven/>
    <context:annotation-config/>

    <bean id="beanGetter" class="cn.jdfo.tool.BeanGetter">
        <property name="beanGetter"><ref bean="beanGetter"></ref></property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test" />
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <!-- //加载实体类的映射文件位置及名称 -->
        <property name="mappingLocations" value="classpath:cn/jdfo/domain/*.hbm.xml"/>
    </bean>

</beans>

上面的文件头需要哪个就添加哪个,如果不知道要哪些,也可以先全部添加完。

context:component-scan标签是自动扫描包,把有注解的配置好的类直接生成bean。

文件下面是几个bean的配置,包括了hibernate的sessionFactory。

现在springMVC基本框架已经搭建好,可以写一个Controller试试成功与否:

@Controller
@RequestMapping(value = "/api")
public class MyController {
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public void saveUser(String name, String email){
        System.out.println("test");
    }
}

启动成功后,访问http://localhost:8080/api/test即可看到效果。

Hadoop框架的搭建

我只记录使用IDEA的方法,eclipse大同小异。

先还是配置hibernate.cfg.xml,然后根据连接好的数据源直接生成对应表的实体类。

配置好hibernate后也可以先试试成功没有,如果成功了那么按照上面配置applicationContext.xml的方法,在里面加入sessionFactory与数据源的bean,hibernate.cfg.xml可选可不选,实体类映射表需要添加。

hibernate配置详见:hibernate入门实例

框架整合实现

现在就可以写各种JAVA代码了:

首先是DAO:

@Repository
public class UserDao {
    @Autowired
    private SessionFactory factory;
    private Session getSession(){return factory.openSession();}

    public void saveUser(User user){
        Session session=getSession();
        Transaction transaction=session.beginTransaction();
        session.save(user);
        transaction.commit();
    }

    public User getUser(int id){
        return getSession().get(User.class,id);
    }

}

然后是Service:

@Service
public class MyService {
    @Autowired
    private UserDao userDao;
    public void saveUser(String name, String email){
        User user=new User(name,email);
        userDao.saveUser(user);
    }

    public User getUser(int id){
        return userDao.getUser(id);
    }
}

最后Controller:

@Controller
@RequestMapping(value = "/api")
public class MyController {
    @Autowired
    private MyService myService;

    @RequestMapping(value = "/saveUser", method = RequestMethod.GET)
    public void saveUser(String name, String email){
        myService.saveUser(name,email);
    }

    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    public User getUser(int id){
        return myService.getUser(id);
    }
}

成功后,下面链接就可以访问:

http://localhost:8080/api/saveUser?name=1111&email=2222

结果:

插入了新的user。

http://localhost:8080/api/getUser?id=2

返回JSON数据:

{"id":2,"name":"woefwe","email":"1314224"}

至此,springMVC框架与Hibernate框架结合完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值