在之前搭建spring mvc项目这篇的基础上继续集成,引入hibernate支持

一、添加jar包引用

修改pom.xml文件,加入:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency> <!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.21.Final</version>
</dependency> <!-- jdbc driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<scope>runtime</scope>
</dependency>

二、添加配置文件

1、在"src/main/resources"代码文件夹中新建文件"demo.properties",内容为:

#mysql database setting
jdbc.type=mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456 #hibernate settings
hibernate.show_sql=true

2、在"src/main/resources"代码文件夹中新建文件"spring-context-hibernate.xml",内容为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <description>Hibernate Configuration</description> <!-- 使用Annotation自动注册Bean -->
<context:component-scan base-package="org.xs.demo1" use-default-filters="false">
<!-- 在父上下文中注册Repository -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan> <!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath*:/demo.properties" /> <!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <!-- 配置SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!-- 动态映射字段 -->
<property name="namingStrategy">
<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
</property>
<!-- 注解扫描的包 -->
<property name="packagesToScan" value="org.xs.demo1" />
</bean>
</beans>

动态映射字段ImprovedNamingStrategy配置以后,Entity实体类里的属性就不需要一个个加@Column注解了,只要命名和表里的一致

三、添加hibernate session过滤器

修改web.xml文件,加入:

<!-- hibernate session过滤器 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

默认情况下server中的方法调用完成后,session就会关闭,等到显示层调用的时候会报错,OpenSessionInViewFilter的效果就是把session的关闭延迟到显示层

四、运行测试

1、建数据库表

CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `test` VALUES ('1', '233');
INSERT INTO `test` VALUES ('2', '666');

2、增加Entity类

package org.xs.demo1;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name="test")
public class testInfo { @Id
private String id; private String name; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

在"src/main/java"代码文件夹的"org.xs.demo1"的包下新建"testInfo.java"类

3、增加Repository类

package org.xs.demo1;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; @Repository
public class testDao { @Autowired
private SessionFactory sessionFactory; @SuppressWarnings("unchecked")
public List<testInfo> getList() { String hql = "from testInfo";
Query query = sessionFactory.getCurrentSession().createQuery(hql); return query.list();
}
}

在"src/main/java"代码文件夹的"org.xs.demo1"的包下新建"testDao.java"类

4、添加Controller方法

@Autowired
private testDao testDao; @RequestMapping("mysql")
public String mysql(HttpServletRequest request) { List<testInfo> list = testDao.getList(); request.setAttribute("testList", list);
request.setAttribute("say", "Hello Mysql!"); return "index3";
}

在HelloController.java中增加"testDao"属性和"mysql"方法

5、增加jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Insert title here</title>
</head>
<body>
<p>${say}</p>
<table border="1" width="100px">
<tr>
<th>列1</th>
<th>列2</th>
</tr>
<tr>
<td>${testList[0].id}</td>
<td>${testList[0].name}</td>
</tr>
<tr>
<td>${testList[1].id}</td>
<td>${testList[1].name}</td>
</tr>
</table>
</body>
</html>

在WEB-INF的views文件夹中新建"index3.jsp"页面

6、运行测试

实例代码地址:https://github.com/ctxsdhy/cnblogs-example

配置hibernate访问mysql的更多相关文章

  1. PHP16 PHP访问MySQL

    学习要点 PHP访问MySQL配置 PHP访问MySQL函数介绍 足球赛程信息管理 PHP访问MySQL配置 PHP.ini配置文件确认以下配置已经打开 extension=php_mysql.dll ...

  2. 在Eclipse中使用JDBC访问MySQL数据库的配置方法

    在Eclipse中使用JDBC访问MySQL数据库的配置方法 分类: DATABASE 数据结构与算法2009-10-10 16:37 5313人阅读 评论(10) 收藏 举报 jdbcmysql数据 ...

  3. MyBatis学习(一)、MyBatis简介与配置MyBatis+Spring+MySql

    一.MyBatis简介与配置MyBatis+Spring+MySql 1.1MyBatis简介 MyBatis 是一个可以自定义SQL.存储过程和高级映射的持久层框架.MyBatis 摒除了大部分的J ...

  4. Maven+Spring+Hibernate+Shiro+Mysql简单的demo框架(二)

    然后是项目下的文件:完整的项目请看  上一篇 Maven+Spring+Hibernate+Shiro+Mysql简单的demo框架(一) 项目下的springmvc-servlet.xml配置文件: ...

  5. MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql

    目录(?)[-] 一MyBatis简介与配置MyBatisSpringMySql MyBatis简介 MyBatisSpringMySql简单配置 搭建Spring环境 建立MySql数据库 搭建My ...

  6. Spring boot通过JPA访问MySQL数据库

    本文展示如何通过JPA访问MySQL数据库. JPA全称Java Persistence API,即Java持久化API,它为Java开发人员提供了一种对象/关系映射工具来管理Java应用中的关系数据 ...

  7. SpringBoot 整合 hibernate 连接 Mysql 数据库

    前一篇搭建了一个简易的 SpringBoot Web 项目,最重要的一步连接数据库执行增删改查命令! 经过了一天的摸爬滚打,终于成功返回数据! 因为原来项目使用的 SpringMVC + Hibern ...

  8. 【译】Spring 4 + Hibernate 4 + Mysql + Maven集成例子(注解 + XML)

    前言 译文链接:http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annot ...

  9. java文件来演示如何访问MySQL数据库

    java文件来演示如何访问MySQL数据库. 注:在命令行或用一个SQL的前端软件创建Database. 先创建数据库: CREATE DATABASE SCUTCS; 接着,创建表: CREATE ...

随机推荐

  1. Java String引起的常量池、String类型传参、“==”、“equals”、“hashCode”问题 细节分析

    在学习javase的过程中,总是会遇到关于String的各种细节问题,而这些问题往往会出现在Java攻城狮面试中,今天想写一篇随笔,简单记录下我的一些想法.话不多说,直接进入正题. 1.String常 ...

  2. ALTER TABLE permission is required on the target table of a bulk copy operation if the table has triggers or check constraints, but 'FIRE_TRIGGERS' or 'CHECK_CONSTRAINTS' bulk hints are not specified

    这个是使用SqlBulkCopy进行批量复制导致的异常,此问题涉及大容量导入数据时,控制大容量导入操作是否执行(触发)触发器.大容量导入操作应只对包含支持多行插入的 INSERT 和 INSTEAD ...

  3. shell习题1

    1------->>>批量创建用户. $#  ---  统计传入参数的数量 $*  ---  传入若干个参数 使用id来确认用户是否存在并创建 向$*进行传参,在运行时加上需要添加的 ...

  4. Linux环境搭建 | 手把手教你配置Linux虚拟机

    在上一节 「手把你教你安装Linux虚拟机」 里,我们已经安装好了Linux虚拟机,在这一节里,我们将配置安装好的Linux虚拟机,使其达到可以开发的程度. Ubuntu刚安装完毕之后,还无法进行开发 ...

  5. 集群、限流、缓存 BAT 大厂无非也就是这么做

    前言 前阵子有网友询问,如何优化网站?这个问题真的很大,跟他简单的聊了一下,随便说了几点,觉得有必要整理一篇文章出来,正好前阵子在做爬虫博客,于是把大体思路分享出来,与大家互通有无,共同进步. 优化 ...

  6. python 22 类与对象

    目录 1. 从空间角度研究类 1.1 添加对象的属性: 1.2 添加类的属性: 1.3 类与对象的关系: 2. 类与类直接的关系 2.1 类与类的关系: 2.2 依赖关系 -- 主从之分 2.3 组合 ...

  7. Zabbix安装时出现缺少PHP模块,解决过程

    我在安装时PHP缺少gettext模块和bcmath模块:一下为解决步骤: 1.进入到PHP源码包目录下的ext目录: #cd /soft/php-/ext 2.会看到ext目录下有gettext目录 ...

  8. hdu 5887 Herbs Gathering (dfs+剪枝 or 超大01背包)

    题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=5887 题解:这题一看像是背包但是显然背包容量太大了所以可以考虑用dfs+剪枝,贪心得到的不 ...

  9. Gym 100851 题解

    A: Adjustment Office 题意:在一个n*n的矩阵,每个格子的的价值为 (x+y), 现在有操作取一行的值,或者一列的值之后输出这个和, 并且把这些格子上的值归0. 题解:模拟, 分成 ...

  10. Hangman Judge UVA - 489

    In ``Hangman Judge,'' you are to write a program that judges a series of Hangman games. For each gam ...