linux系统:CentOS6.4安装mysql5.6.14
windows系统: 下载msi文件图形界面安装mysql 或者下载zip配置环境变量后启动
Maven安装----在Windows上安装Maven
<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>springMVC</groupId> <artifactId>springMVC</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name/> <description/> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.apache.openejb</groupId> <artifactId>javaee-api</artifactId> <version>5.0-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> </project>
一般创建出来的项目,只有src/main/java,然后我们加上其他的三项(必须是新建Source Folder!src/main/resources; src/test/resources; src/test/java)
接着我们在src/main/java文件夹下建立我们的包, 后面springMVC配置需要到这几个路径
我这里建了
com.tianyan.web.controller存放控制器路由
com.tianyan.domain.dao存放数据库相关操作的服务
com.tianyan.domain.service存放业务操作的服务
com.tianyan.domain.entity存放实体
目录结构如图:
最后在src/main/webapp/WEB-INF下新建一个存放视图文件的文件夹,新建一个test.jsp
我们需要在maven的pom.xml中添加包的引用,maven就会自动下载相关的包。
我们添加的包如下:
<!-- mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- aspectjweaver.jar这是Spring AOP所要用到的包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.1</version>
</dependency>
<!-- hibernate4 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<!-- spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<!-- spring3 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<!--jsp页面使用的jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
把以上代码放在<dependencies></dependencies> 之间,得到最终的pom.xml内容如下:
<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>springMVC</groupId> <artifactId>springMVC</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name/> <description/> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.apache.openejb</groupId> <artifactId>javaee-api</artifactId> <version>5.0-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <!-- mysql数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> <!-- aspectjweaver.jar这是Spring AOP所要用到的包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.1</version> </dependency> <!-- hibernate4 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <!-- spring mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.0.RELEASE</version> </dependency> <!-- spring3 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.0.RELEASE</version> </dependency> <!--jsp页面使用的jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> </project>
新建一个xml文件,并且配置启用spring mvc的注解,使用注解的路径以及视图模式等。
在src/main/resources路径下新建xml文件命名为springMVC.xml,如图:
新建的xml文件只有<?xml version="1.0" encoding="UTF-8"?>,我们把内容修改成我们的配置,如下:
<?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:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 支持注解 --> <mvc:annotation-driven /> <!--自动装配DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <mvc:default-servlet-handler /> <!-- 设置自动扫描的路径,用于自动注入bean 这里的路径与自己的项目目录对应--> <!-- 扫描controller路由控制器 --> <context:component-scan base-package="com.tianyan.web.controller" /> <context:component-scan base-package="com.tianyan.domain.dao,com.tianyan.domain.service" /> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="suffix" value=".jsp" /> <!-- 视图文件类型 --> <property name="prefix" value="/WEB-INF/views" /> <!-- 视图文件的文件夹路径 --> </bean> </beans>
mysql配置文件主要是记录mysql的地址,帐号密码等。在这个配置文件中可以看到注释了其它数据库引擎,如果有需要,可以相应配置:
在src/main/resources路径下新建一个命名为config.properties文件:
以上参数分别代表了mysql连接的地址 端口 数据库名 以及帐号密码。
#\u5C5E\u6027\u6587\u4EF6 #Oracle \u7684\u914D\u7F6E #hibernate.dialect=org.hibernate.dialect.OracleDialect #driverClassName=oracle.jdbc.driver.OracleDriver #validationQuery=SELECT 1 FROM DUAL #jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl #jdbc_username= #jdbc_password= #SQLServer \u7684\u914D\u7F6E #hibernate.dialect=org.hibernate.dialect.SQLServerDialect #driverClassName=net.sourceforge.jtds.jdbc.Driver #validationQuery=SELECT 1 #jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy #jdbc_username= #jdbc_password= #Derby \u7684\u914D\u7F6E #hibernate.dialect=org.hibernate.dialect.DerbyDialect #driverClassName=org.apache.derby.jdbc.EmbeddedDriver #validationQuery=SELECT 1 #jdbc_url=jdbc:derby:sy;create=true #jdbc_username= #jdbc_password= #MySQL \u7684\u914D\u7F6E hibernate.dialect=org.hibernate.dialect.MySQLDialect driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 jdbc_url=jdbc\:mysql\://localhost\:3306/tianyan?useUnicode\=true&characterEncoding\=utf-8 jdbc_username=root jdbc_password= hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false sessionInfoName=sessionInfo uploadFieldName=filedata uploadFileMaxSize=20971520 uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid uploadDirectory=attached
在src/main/resources路径下新建xml文件命名为spring-hibernate.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd "> <!-- JNDI(通过Tomcat)方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 配置数据源 这里class可以使用不同的驱动--> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="current_session_context_class">thread</prop> <prop key="hibernate.connection.driver_class" >${driverClassName}</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="packagesToScan"> <list> <!-- 此处与entity实体路径对应 --> <value>com.tianyan.domain.entity</value> </list> </property> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 注解方式配置事物 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
原项目中在src/main/webapp中已有web.xml,不需要再新建,我们需要把前面新建的 springMVC.xml,spring-hibernate.xml(名称与自己的前面的命名统一)配置引用。
增加如下内容:
<!-- spring hibernate -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-hibernate.xml</param-value>
</context-param>
<!-- openSessionInView配置 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--spring mvc 配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.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>
<!-- encodeing -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- encoding filter for jsp page -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
配置如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- spring hibernate --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-hibernate.xml</param-value> </context-param> <!-- openSessionInView配置 --> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--spring mvc 配置 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.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> <!-- encodeing --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!-- encoding filter for jsp page --> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
到这里我们的环境就算搭建完成了。已经可以在代码中使用注解和自动注解了。
<!-- 注解方式配置事物 -->
<tx:annotation-driven transaction-manager="transactionManager" />
这句涉及到事物的注解 @Transactional 的使用。增加@Transactional注解 后 具有 事物的特性。
<!-- 自动扫描注解方式配置的hibernate类文件 -->
<property name="packagesToScan">
<list>
<!-- 此处与entity实体路径对应 -->
<value>com.tianyan.domain.entity</value>
</list>
</property>
这一段涉及到 实体的注解 @Entity @Table(name="xxx") 的使用。增加@Entity 注解 后 具有 实体的特性。
<context:component-scan base-package="com.tianyan.web.controller" />
这一句涉及到路由注解 @Controller 的使用,注解后具有路由的特性。
<context:component-scan base-package="com.tianyan.domain.dao,com.tianyan.domain.service" />
这一句涉及到服务注解 @Repository 和@Service( "xxx" ) 的使用,注解后具有服务的特性。
在mysql中新建数据库tianyan,我使用的是mysql-front工具连接mysql后新建如下:
然后在项目右键---》Properties-----》 web 中 把项目名去掉 修改成/ ,如图:
package com.tianyan.domain.dao.impl; import java.io.Serializable; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.tianyan.domain.dao.ShareDataDao; import com.tianyan.domain.entity.ShareData; /** * * @ClassName: ShareDataDaoImpl * @Description: 股票数据数据库操作服务---注解成@Repository * @author joe * @date 2015-11-19 * */ @Repository @Transactional public class ShareDataDaoImpl implements ShareDataDao{ @Autowired SessionFactory sessionFactory; public Serializable save(ShareData shareData) { Session session=sessionFactory.getCurrentSession(); return session.save(shareData); } }
package com.tianyan.domain.dao; import java.io.Serializable; import com.tianyan.domain.entity.ShareData; public interface ShareDataDao { Serializable save(ShareData shareData); }
package com.tianyan.domain.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * * @ClassName: ShareData * @Description:数据实体 * @author joe * @date 2015-11-18 * */ @Entity @Table (name="share_data") public class ShareData { @Id @GeneratedValue private int id; private String shareType; private String shareCode; private String shareName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getShareType() { return shareType; } public void setShareType(String shareType) { this.shareType = shareType; } public String getShareCode() { return shareCode; } public void setShareCode(String shareCode) { this.shareCode = shareCode; } public String getShareName() { return shareName; } public void setShareName(String shareName) { this.shareName = shareName; } }
package com.tianyan.domain.service.impl; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.tianyan.domain.dao.ShareDataDao; import com.tianyan.domain.entity.ShareData; import com.tianyan.domain.service.ShareDataService; /** * * @ClassName: ShareDataServiceImpl * @Description:股票数据业务实现---注解为服务@Service和事物@Transactional * @author joe * @date 2015-11-19 * */ @Service @Transactional public class ShareDataServiceImpl implements ShareDataService{ @Autowired ShareDataDao shareDataDao; public Serializable insertData(ShareData shareData) { return shareDataDao.save(shareData); } }
package com.tianyan.domain.service; import java.io.Serializable; import com.tianyan.domain.entity.ShareData; public interface ShareDataService { Serializable insertData(ShareData shareData); }
package com.tianyan.web.controller; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.tianyan.domain.entity.ShareData; import com.tianyan.domain.service.ShareDataService; /** * * @ClassName: IndexController * @Description:首页路由 ---注解@Controller * @author joe * @date 2015-11-19 * */ @Controller public class IndexController { @Autowired ShareDataService shareDataService; @RequestMapping("/testInDb") public String testInDb(Model model){ ShareData shareData=new ShareData(); shareData.setShareCode("00023"); shareData.setShareName("万科"); shareData.setShareType("SZ"); Serializable result=shareDataService.insertData(shareData); model.addAttribute("result", result); return "/test"; } }
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'test.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> ${result}<br> </body> </html>
启动服务之后在浏览器中 访问 (端口号对应自己的tomcat设置,我这里用的9000) 结果如下:
成功写入。
在xml中使用context:property-placeholder报错说找不到,有可能是头部标准库未引入。要注意加上
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
如图:
首先要确保 controller扫描路径对应
如果仍然无效,则需要检查是不是使用了<context:annotation-config />开启注解。
修改成
<!-- 支持注解 --> <mvc:annotation-driven />
可用。
这应该是版本或者引入标准库不一样导致的问题。
我们这旧版本hibernate中一般是使用hibernateTemplate注入来进行数据存取。
如下:
spring-hibernate.xml
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean>dao文件中的运用如下:
/** * * @ClassName: ShareDataDaoImpl * @Description: 股票数据数据库操作服务---注解成@Repository * @author joe * @date 2015-11-19 * */ @Repository public class ShareDataDaoImpl implements ShareDataDao{ @Autowired HibernateTemplate hibernateTemplate; public String save(ShareData shareData) { return (String) hibernateTemplate.save(shareData); } }
java.lang.NoSuchMethodError:org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session
原因:hibernate4之后,spring3.1把HibernateDaoSupport去除,包括数据访问都不需要hibernatetemplate,这意味着dao需要改写,直接使用hibernate的session和query接口。
如果你的配置还是hibernate3,需要改为hibernate4
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
--------------------------------------------------------------------
由于Hibernate4已经完全可以实现事务了, 与Spring3.1中的hibernatedao,hibernateTemplete等有冲突,所以Spring3.1里已经不提供Hibernatedaosupport,HibernateTemplete了,只能用Hibernate原始的方式用session:
Session session = sessionFactory.openSession();
Session session = sessionFactory.getCurrentSession();
在basedao里可以用注入的sessionFactory获取session.
注意, 配置事务的时候必须将父类baseServiceImpl也配上,要不然会出现错误:No Session found for currentthread, 以前是不需要的
SessionFactory.getCurrentSession()的后台实现是可拔插的。因此,引入了新的扩展接口 (org.hibernate.context.spi.CurrentSessionContext)和
新的配置参数(hibernate.current_session_context_class),以便对什么是“当前session”的范围和上下文(scope and context)的定义进行拔插。
在Spring @Transactional声明式事务管理,”currentSession”的定义为: 当前被 Spring事务管理器 管理的Session,此时应配置:
hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext。
此处一定注意 使用 hibernate4,在不使用OpenSessionInView模式时,在使用getCurrentSession()时会有如下问题: 当有一个方法list 传播行为为Supports,当在另一个方法getPage()(无事务)调用list方法时会抛出org.hibernate.HibernateException: No Session found for current thread 异常。 这是因为getCurrentSession()在没有session的情况下不会自动创建一个,不知道这是不是Spring3.1实现的bug。 因此最好的解决方案是使用REQUIRED的传播行为。
解决办法:
去掉spring-hibernate.xml中hibernateTemplate的定义
dao类中直接使用sessionFactory注入如下:
package com.tianyan.domain.dao.impl; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tianyan.domain.dao.ShareDataDao; import com.tianyan.domain.entity.ShareData; /** * * @ClassName: ShareDataDaoImpl * @Description: 股票数据数据库操作服务---注解成@Repository * @author joe * @date 2015-11-19 * */ @Repository public class ShareDataDaoImpl implements ShareDataDao{ @Autowired SessionFactory sessionFactory; public String save(ShareData shareData) { Session session=sessionFactory.getCurrentSession(); return (String) session.save(shareData); } }
解决上述问题NoSuchMethodError: org.hibernate.SessionFactory.openSession()后发现又暴了No Session found for current thread这个错误。
原因是采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()创建的session则不会如果采用的时Hibernate4,使用getCurrentSession()必须配置事务,否则无法取到session。
事务的配置有两种方式:
一是拦截方式:
spring-hibernate.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd "> <!-- JNDI(通过Tomcat)方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 配置数据源 这里class可以使用不同的驱动--> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="current_session_context_class">thread</prop> <prop key="hibernate.connection.driver_class" >${driverClassName}</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="packagesToScan"> <list> <!-- 此处与entity实体路径对应 --> <value>com.tianyan.domain.entity</value> </list> </property> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="modify*" propagation="REQUIRED"/> <tx:method name="edit*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED"/> <tx:method name="repair" propagation="REQUIRED"/> <tx:method name="deleteAndRepair" propagation="REQUIRED"/> <tx:method name="get*" propagation="REQUIRED" /> <tx:method name="find*" propagation="REQUIRED" /> <tx:method name="load*" propagation="REQUIRED" /> <tx:method name="search*" propagation="REQUIRED" /> <tx:method name="datagrid*" propagation="REQUIRED" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.tianyan.domain.dao..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
而且这里Propagation必须为required。
Spring中Propagation类的事务属性详解:
PROPAGATION_REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
PROPAGATION_SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
PROPAGATION_NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。
二是自动注解方式:
自动注解方式比较简单,推荐。
spring-hibernate.xml中使用
<!-- 注解方式配置事物 -->
<tx:annotation-driven transaction-manager="transactionManager" />
完整spring-hibernate.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd "> <!-- JNDI(通过Tomcat)方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 配置数据源 这里class可以使用不同的驱动--> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="current_session_context_class">thread</prop> <prop key="hibernate.connection.driver_class" >${driverClassName}</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="packagesToScan"> <list> <!-- 此处与entity实体路径对应 --> <value>com.tianyan.domain.entity</value> </list> </property> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 注解方式配置事物 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
dao的class中使用@Transactional,如下:
package com.tianyan.domain.dao.impl; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.tianyan.domain.dao.ShareDataDao; import com.tianyan.domain.entity.ShareData; /** * * @ClassName: ShareDataDaoImpl * @Description: 股票数据数据库操作服务---注解成@Repository * @author joe * @date 2015-11-19 * */ @Repository @Transactional public class ShareDataDaoImpl implements ShareDataDao{ @Autowired SessionFactory sessionFactory; public String save(ShareData shareData) { Session session=sessionFactory.getCurrentSession(); return (String) session.save(shareData); } }
检查
<prop key="current_session_context_class">thread</prop>
是否已经有了,是否书写正确。(上面完整版中能找到对应位置)。
最后还需要在web.xml中添加org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
<!-- openSessionInView配置 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
就能顺利解决这个问题。
完整版web.xml如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- spring hibernate --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-hibernate.xml</param-value> </context-param> <!-- openSessionInView配置 --> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--spring mvc 配置 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.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> <!-- encodeing --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!-- encoding filter for jsp page --> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
找不到驱动.....
检查是否pom.xml中是否引用了
<!-- mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
以及jdbc_url=jdbc\:mysql\://127.0.0.1\:3306/test
是否书写有误.
如果都确认无误还是报错,需要把mysql-connector-java的jar包放到 本地的jdk路径下,例如我的路径是:
C:\Program Files (x86)\Java\jdk1.7.0_13\jre\lib\ext
确实很奇葩 但是成功解决了。
ps:
如果把驱动加到ext文件夹后启动还是报错,有可能myeclipse使用的不是这一个jdk,则需要检查myeclip---》preference---》java---》installed jres中的jdk路径是否对应。
或者在文件系统中搜索jre文件夹。只要结构类似的文件夹都放入驱动。这样无论myeclipse使用哪个jdk 都会加载到驱动。
hibernate没有自动建表。
需要在配置sessionFactory的hibernateProperties时加上参数
<prop key="hibernate.hbm2ddl.auto">update</prop>
如果update是在配置文件中配置的 记得 不能有空格。
update:表示自动根据model对象来更新表结构,启动hibernate时会自动检查数据库,如果缺少表,则自动建表;如果表里缺少列,则自动添加列。
还有其他的参数:
create:启动hibernate时,自动删除原来的表,新建所有的表,所以每次启动后的以前数据都会丢失。
create-drop:启动hibernate时,自动创建表,程序关闭时,自动把相应的表都删除。所以程序结束时,表和数据也不会再存在。
PS:数据库要预先建立好,因为hibernate只会建表,不会建库
代码下载
http://download.csdn.net/detail/q383965374/9290425