利用Spring Roo搭建spring/springMVC/jpa(hibernate)

之前看spring实战的时候,书中提到spring roo工具,一直没有来得及尝试. 这次十一,我和女友一致认为前两天人太挤出去是受罪,于是就窝在了家里,就有了点时间来研究一下技术.

好了,言归正传 ,我比较懒,所以一直在寻找最简单的办法去完成一些事情. 对于框架集成也是如此 ,已经尝试过各种方法了,就是为了寻找更简单,实用.

本次是利用Spring Roo进行搭建,认为是目前最简单的了,并且Roo的配置几乎都是最佳实践.

-------------------------------PART1,Roo部分--------------------------------

1  下载好Roo并解压缩,我的Roo是1.2.5

环境变量:path下有  %ROO_HOME%\bin,   ROO_HOME指向Roo的解压目录.

打开cmd测试一下, 看到下图的样子说明Roo已经配置成功了.

2 在你想要创建工程的地方建一个文件夹,我这里建的文件夹是 springmvc-roo.

3 进入这个文件夹,按住shift+鼠标左键,选择"在此处打开窗口",弹出cmd窗口,输入roo,略等一下,它要进行下载,等到光标停留在 Roo>的后面,说明已经准备就绪了.

4 键入 hint,查看提示

5创建工程

输入proj,Tab一下让其补全为project, 再Tab一下, 自动后补 --topLevelPackage, 这个参数表示顶级层的package,我这里输入为com.ll.demo

这时候如果再Tab,发现没反应, 有一个技巧,就是 键入-- ,再Tab一下, 就会给出几个选项

好了,知道有什么选项的话就简单了, 这里我在后面键入 projectName 然后空格,跟上自己的projectName,我这里即为springmvc-roo

(注意:如果不指定projectName,它会自动生成为demo,我不喜欢看到这个名字,所以一般会改掉.)

输入后就可以直接回车了,这时就会自动建一个工程出来,如下图

第一条命令:project --topLevelPackage com.ll.demo --projectName springmvc-roo

6 配置jpa的提供者和选择相应的数据库

先hint一下,看看提示,基本上就知道怎么做了

我用的是jpa+hibernate实现,所以键入

jpa setup Tab一下, 再键入--providor ,Tab一下,这时可以看到jpa的几个提供者

这里我选择HIBERNATE(输入H,Tab一下自动补全)

再次Tab一下, 显示为

我要看有哪些数据库所以我再Tab一下,就可以看到有好多数据库可以选择

这里我选择Oracle,回车

可以看到已经做了相应的配置了.

其实这一步后面可以直接跟上数据库明以及用户和密码,我这里给忘了,忘了的话一会要在database.properties里面更改.

第二条命令:jpa setup --provider HIBERNATE --database ORACLE

7 配置entity

(其实这一步做了等于没做,因为我试了数次,发现创建不了包,这里只是记录一下方法)

如果想不起来要干什么,输入hint可以查看一下,Roo会对你做的东西记录下来,并且提举你的操作只能提示下一步.

hint一下,可以看到如下图

它告诉我们要建entity之类的,这里我不做复杂配置,就建一个简单的User类就好,不配置字段.

连续键入知道命令为下图这样~代表上面创建的顶层包名,我这里加了一个domain包.

8 配置SpringMVC

在 Roo>根目录下,Tab一下,可以看到Roo所支持的所有命令

我这里比较有用的是 controller和logger

controller可以帮助我们创建springMVC配置

好了,接下来继续知道下图的命令:

可以看到已经进行了SpringMVC的配置

9 配置日志

键入下图的命令

进行了日志的配置.

至此,项目的Roo的任务就完成了,这时已经有了一个基本的项目骨架了.

----------------------------------PART2,ide部分-------------------------

10 导入项目

我们将springmvc-roo项目导入到eclipse,看看Roo为我们创建的项目结构是什么样子的.因为Roo为我们创建的是一个maven,所以我们用maven方式导入,

需要说明的是,第一次导入的时候比较慢,需要下载一些东西

每次这里都是卡一会

好了,成功了,看看原始的目录

可以从上图发现,我建的那些包和类都出来,甚至src/main/java都没出来.

哎,还是有bug啊,坑货,

没办法,自己来吧

11 弥补Roo的缺陷

在src/main新建Java文件夹,这时候去build path下看,src/main/java应该出来了,如果没有的话就手动加一下吧.

12 解决ojdbc依赖包的问题

如果看看problem,就会发现下面这个错误

注意一点,如果是Oracle的话,那个ojdbc14.jar是maven不能下载的,应该是收费的.

我在上一次配的时候自己网上找了个ojdbc14.jar已经配置到本地库了,但是跟这个pom引入的名字不一样,所以我改下pom的那个依赖版本号

下面是我maven库里的,可以看到version少了一位.我在pom里加上最后一位0

保存,发现那个错误已经没了

13添加自己想要的springMVC解析器

由于Roo生成的webmvc-config.xml没有我想要的解析器,所以我要加上我自己的.

    <!-- 添加解析器 -->
    <beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

然后保存,这里会发现又多了一个错误

说是beans:bean 有问题.这里经过搜索,解决办法是在该文件的xmlns声明的地方加上

xmlns:beans="http://www.springframework.org/schema/beans"

发现问题已经解决如下图

14 添加顶层包

看下图可以发现我们Roo敲得名没有为我们创建,这里我自己加一下吧.

新建package:com.ll.demo,再在包建domain,controller,service及impl包

15导入现成的类

按照如下目录进行导入我的类

导入我的现成的类:User.java ,HomeController.java,UserService.java,UserServiceImpl.java,home.jsp,res.jsp

这几个类的内容如下

User.java

package com.ll.demo.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name="t_user")
public class User implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_t_user")
	@SequenceGenerator(name="seq_t_user",sequenceName="seq_t_user")
	@Column(name="id")
	private Long id;

	@Column(name="name")
	private String name;

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

}

HomeController.java

package com.ll.demo.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestMethod;

import com.ll.demo.domain.User;
import com.ll.demo.service.UserService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);

	@Autowired
	private UserService userService;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
				DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		model.addAttribute("serverTime", formattedDate);
		return "home";
	}

	@RequestMapping(value = "/testjpa", method = RequestMethod.GET)
	public String testJpa(Model model) {
		User u = new User();
		u.setName("uuuu123");
		this.userService.save(u);
		return "res";
	}

	@RequestMapping(value = "/find", method = RequestMethod.GET)
	public String find(Model model){
		User user = this.userService.findById(50L);
		model.addAttribute("msg", user.getName());
		return "res";
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}

UserSerivce.java

package com.ll.demo.service;

import com.ll.demo.domain.User;

public interface UserService {

	void save(User user);

	User findById(Long id);

	User findByName(String name);
}

UserServiceImpl.java

package com.ll.demo.service.impl;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ll.demo.domain.User;
import com.ll.demo.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private EntityManagerFactory entityManagerFactory;

	@Override
	public void save(User user) {
		EntityManager em = entityManagerFactory.createEntityManager();
		em.getTransaction().begin();
		em.persist(user);
		em.getTransaction().commit();
	}

	@Override
	public User findById(Long id) {
		return entityManagerFactory.createEntityManager().find(User.class, id);
	}

	@Override
	public User findByName(String value) {
		return (User) this.entityManagerFactory.createEntityManager()
				.createQuery("from User where name =:name ")
				.setParameter("name", value);
	}

	public EntityManagerFactory getEntityManagerFactory() {
		return entityManagerFactory;
	}

	public void setEntityManagerFactory(
			EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}

}

home.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
<h1>
	Hello world!
</h1>

<P>  The time on the server is ${serverTime}. </P>
</body>
</html>

res.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
result pages
<hr>

<P>  The result of you opering: ${msg}. </P>
</body>
</html>

16 至此编码就完成了

下面用maven跑一下

好的,没问题

17 发布,运行

加入tomcat,运行,看看报错不.

一次成功,呵呵,这次气场不错哦.

18 浏览器测试

输入http://localhost:8080/springmvc-roo/testjpa

后面报错

该死,应该是database.properties没配,那会说要配的.

果然如此:

改动如下:

重启tomcat,启动之余来看看一下t_user表

无记录,按说是有记录的,看来是persistence下的 <property name="hibernate.hbm2ddl.auto" value="create"/>到的鬼,先不管了.先测试吧

输入http://localhost:8080/springmvc-roo/testjpa

ok,再看一下后台:

数据有了.

成功!

项目下载

附录其他的配置文件--------------------------------------------------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------------------------------------------------

pom.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ll.demo</groupId>
	<artifactId>springmvc-roo</artifactId>
	<packaging>war</packaging>
	<version>0.1.0.BUILD-SNAPSHOT</version>
	<name>springmvc-roo</name>
	<properties>
		<aspectj.version>1.7.4</aspectj.version>
		<java.version>1.6</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<roo.version>1.2.5.RELEASE</roo.version>
		<slf4j.version>1.7.5</slf4j.version>
		<spring.version>3.2.6.RELEASE</spring.version>
	</properties>
	<repositories>
		<repository>
			<id>spring-maven-release</id>
			<name>Spring Maven Release Repository</name>
			<url>http://maven.springframework.org/release</url>
		</repository>
		<repository>
			<id>spring-maven-milestone</id>
			<name>Spring Maven Milestone Repository</name>
			<url>http://maven.springframework.org/milestone</url>
		</repository>
		<repository>
			<id>spring-roo-repository</id>
			<name>Spring Roo Repository</name>
			<url>http://spring-roo-repository.springsource.org/release</url>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>spring-maven-release</id>
			<name>Spring Maven Release Repository</name>
			<url>http://maven.springframework.org/release</url>
		</pluginRepository>
		<pluginRepository>
			<id>spring-maven-milestone</id>
			<name>Spring Maven Milestone Repository</name>
			<url>http://maven.springframework.org/milestone</url>
		</pluginRepository>
		<pluginRepository>
			<id>spring-roo-repository</id>
			<name>Spring Roo Repository</name>
			<url>http://spring-roo-repository.springsource.org/release</url>
		</pluginRepository>
	</pluginRepositories>
	<dependencies>
		<!-- General dependencies for standard applications -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${aspectj.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${aspectj.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>net.sf.flexjson</groupId>
			<artifactId>flexjson</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.1</version>
		</dependency>
		<!-- ROO dependencies -->
		<dependency>
			<groupId>org.springframework.roo</groupId>
			<artifactId>org.springframework.roo.annotations</artifactId>
			<version>${roo.version}</version>
			<scope>provided</scope>
		</dependency>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.5.0</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.2.2.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.2.2.Final</version>
			<exclusions>
				<exclusion>
					<groupId>cglib</groupId>
					<artifactId>cglib</artifactId>
				</exclusion>
				<exclusion>
					<groupId>dom4j</groupId>
					<artifactId>dom4j</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.0-api</artifactId>
			<version>1.0.1.Final</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.3.1.Final</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>
		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
				<exclusion>
					<groupId>xml-apis</groupId>
					<artifactId>xml-apis</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.webflow</groupId>
			<artifactId>spring-js-resources</artifactId>
			<version>2.2.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>commons-digester</groupId>
			<artifactId>commons-digester</artifactId>
			<version>2.1</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>jstl-api</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>jstl-impl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.el</groupId>
			<artifactId>el-api</artifactId>
			<version>2.2</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>1.6</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.5</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.2</version>
				<!-- <configuration> <webXml>target/web.xml</webXml> </configuration> -->
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>aspectj-maven-plugin</artifactId>
				<version>1.4</version>
				<dependencies>
					<!-- NB: You must use Maven 2.0.9 or above or these are ignored (see
						MNG-2972) -->
					<dependency>
						<groupId>org.aspectj</groupId>
						<artifactId>aspectjrt</artifactId>
						<version>${aspectj.version}</version>
					</dependency>
					<dependency>
						<groupId>org.aspectj</groupId>
						<artifactId>aspectjtools</artifactId>
						<version>${aspectj.version}</version>
					</dependency>
				</dependencies>
				<executions>
					<execution>
						<phase>process-sources</phase>
						<goals>
							<goal>compile</goal>
							<goal>test-compile</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<outxml>true</outxml>
					<aspectLibraries>
						<aspectLibrary>
							<groupId>org.springframework</groupId>
							<artifactId>spring-aspects</artifactId>
						</aspectLibrary>
					</aspectLibraries>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<!-- Aspects in src/main/java and src/main/aspects are added as default
						in the compile goal. Aspects in src/test/java and src/test/aspects are added
						as default in the test-compile goal. Aspects in src/main/java are added in
						the test-compile goal if weaveWithAspectsInMainSourceFolder is set to true -->
					<weaveWithAspectsInMainSourceFolder>false</weaveWithAspectsInMainSourceFolder>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.12</version>
				<configuration>
					<printSummary>false</printSummary>
					<redirectTestOutputToFile>true</redirectTestOutputToFile>
					<excludes>
						<exclude>**/*_Roo_*</exclude>
					</excludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-deploy-plugin</artifactId>
				<version>2.7</version>
			</plugin>
			<!-- IDE -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.7</version>
				<!-- Note 2.8 does not work with AspectJ aspect path -->
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
					<additionalBuildcommands>
						<buildCommand>
							<name>org.eclipse.ajdt.core.ajbuilder</name>
							<arguments>
								<aspectPath>org.springframework.aspects</aspectPath>
							</arguments>
						</buildCommand>
						<buildCommand>
							<name>org.springframework.ide.eclipse.core.springbuilder</name>
						</buildCommand>
					</additionalBuildcommands>
					<additionalProjectnatures>
						<projectnature>org.eclipse.ajdt.ui.ajnature</projectnature>
						<projectnature>com.springsource.sts.roo.core.nature</projectnature>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-idea-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<dependenciesAsLibraries>true</dependenciesAsLibraries>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>8.1.4.v20120524</version>
				<configuration>
					<webAppConfig>
						<contextPath>/${project.name}</contextPath>
					</webAppConfig>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

webmvc-config.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.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.1.xsd">

    <!-- The controllers are autodetected POJOs labeled with the @Controller annotation. -->
    <context:component-scan base-package="com.ll.demo" use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
    </context:component-scan>

    <!-- Turns on support for mapping requests to Spring MVC @Controller methods
         Also registers default Formatters and Validators for use across all @Controllers -->
    <mvc:annotation-driven/>

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources -->
    <mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>

    <!-- Allows for mapping the DispatcherServlet to "/" by forwarding static resource
    requests to the container‘s default Servlet -->
    <mvc:default-servlet-handler/>

    <!-- Register "global" interceptor beans to apply to all registered HandlerMappings -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
    </mvc:interceptors>

    <!-- Selects a static view for rendering without the need for an explicit controller -->
    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/uncaughtException"/>
    <mvc:view-controller path="/resourceNotFound"/>
    <mvc:view-controller path="/dataAccessFailure"/>

    <!-- Resolves localized messages*.properties and application.properties files in the application to allow for internationalization.
    The messages*.properties files translate Roo generated messages which are part of the admin interface, the
    application.properties resource bundle localizes all application specific messages such as entity names and menu items. -->
    <bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource" p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application" p:fallbackToSystemLocale="false"/>

    <!-- Store preferred language configuration in a cookie -->
    <bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" id="localeResolver" p:cookieName="locale"/>

    <!-- Resolves localized <theme_name>.properties files in the classpath to allow for theme support -->
    <bean class="org.springframework.ui.context.support.ResourceBundleThemeSource" id="themeSource"/>

    <!-- Store preferred theme configuration in a cookie -->
    <bean class="org.springframework.web.servlet.theme.CookieThemeResolver" id="themeResolver" p:cookieName="theme" p:defaultThemeName="standard"/>

    <!-- This bean resolves specific types of exceptions to corresponding logical - view names for error views.
    The default behaviour of DispatcherServlet - is to propagate all exceptions to the servlet
    container: this will happen - here with all other types of exceptions. -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:defaultErrorView="uncaughtException">
        <property name="exceptionMappings">
            <props>
                <prop key=".DataAccessException">dataAccessFailure</prop>
                <prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop>
                <prop key=".TypeMismatchException">resourceNotFound</prop>
                <prop key=".MissingServletRequestParameterException">resourceNotFound</prop>
            </props>
        </property>
    </bean>

    <!-- Enable this for integration of file upload functionality -->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"/>

    <!-- 添加解析器 -->
    <beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
</beans>

log4.properties

#Updated at Fri Oct 03 00:11:10 CST 2014
#Fri Oct 03 00:11:10 CST 2014
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.rootLogger=DEBUG, stdout
log4j.appender.R.File=application.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.R=org.apache.log4j.RollingFileAppender

persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
            <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.connection.charSet" value="UTF-8"/>
            <!-- Uncomment the following two properties for JBoss only -->
            <!-- property name="hibernate.validator.apply_to_ddl" value="false" /-->
            <!-- property name="hibernate.validator.autoregister_listeners" value="false" /-->
        </properties>
    </persistence-unit>
</persistence>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!--
        This will automatically locate any and all property files you have
        within your classpath, provided they fall under the META-INF/spring
        directory. The located property files are parsed and their values can
        then be used within application context files in the form of
        ${propertyKey}.
    -->
    <context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
    <!--
        Turn on AspectJ @Configurable support. As a result, any time you
        instantiate an object, Spring will attempt to perform dependency
        injection on that object. This occurs for instantiation via the "new"
        keyword, as well as via reflection. This is possible because AspectJ
        is used to "weave" Roo-based applications at compile time. In effect
        this feature allows dependency injection of any object at all in your
        system, which is a very useful feature (without @Configurable you‘d
        only be able to dependency inject objects acquired from Spring or
        subsequently presented to a specific Spring dependency injection
        method). Roo applications use this useful feature in a number of
        areas, such as @PersistenceContext injection into entities.
    -->
    <context:spring-configured/>
    <!--
        This declaration will cause Spring to locate every @Component,
        @Repository and @Service in your application. In practical terms this
        allows you to write a POJO and then simply annotate the new POJO as an
        @Service and Spring will automatically detect, instantiate and
        dependency inject your service at startup time. Importantly, you can
        then also have your new service injected into any other class that
        requires it simply by declaring a field for your service inside the
        relying class and Spring will inject it. Note that two exclude filters
        are declared. The first ensures that Spring doesn‘t spend time
        introspecting Roo-specific ITD aspects. The second ensures Roo doesn‘t
        instantiate your @Controller classes, as these should be instantiated
        by a web tier application context. Refer to web.xml for more details
        about the web tier application context setup services.

        Furthermore, this turns on @Autowired, @PostConstruct etc support. These
        annotations allow you to use common Spring and Java Enterprise Edition
        annotations in your classes without needing to do any special configuration.
        The most commonly used annotation is @Autowired, which instructs Spring to
        dependency inject an object into your class.
    -->
    <context:component-scan base-package="com.ll.demo">
        <context:exclude-filter expression=".*_Roo_.*" type="regex"/>
        <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
    </context:component-scan>
    <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
        <property name="driverClassName" value="${database.driverClassName}"/>
        <property name="url" value="${database.url}"/>
        <property name="username" value="${database.username}"/>
        <property name="password" value="${database.password}"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
        <property name="testWhileIdle" value="true"/>
        <property name="timeBetweenEvictionRunsMillis" value="1800000"/>
        <property name="numTestsPerEvictionRun" value="3"/>
        <property name="minEvictableIdleTimeMillis" value="1800000"/>
        <property name="validationQuery" value="SELECT 1 FROM DUAL"/>
    </bean>
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property name="persistenceUnitName" value="persistenceUnit"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

database.properties

#Updated at Thu Oct 02 23:53:27 CST 2014
#Thu Oct 02 23:53:27 CST 2014
database.driverClassName=oracle.jdbc.OracleDriver
database.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl
database.username=roo
database.password=roo
时间: 2024-10-11 05:59:48

利用Spring Roo搭建spring/springMVC/jpa(hibernate)的相关文章

maven 聚合工程 用spring boot 搭建 spring cloud 微服务 模块式开发项目

项目的简单介绍: 项目采用maven聚合工程 用spring boot 搭建 spring cloud的微服务 模块式开发 项目的截图: 搭建开始: 能上图 我少打字 1.首先搭建maven的聚合工程 1.1创建聚合工程的父模块 1.2设置父模块的POM文件 主要是配置 spring boot版本,spring cloud 版本,和一些通用的依赖 比如这里的 lombok依赖 <?xml version="1.0" encoding="UTF-8"?>

spring 02-Maven搭建Spring开发环境

1.搭建Maven的web项目 2.创建相关文件 3.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/maven

1.2 Spring环境搭建--Spring源码深度解析

前言: Spring 的源码已经从 svn 迁移到 GitHub.而且也改为基于 Gradle 的构建来构建项目.它取代了之前的 Ant+Ivy 系统,所以要构建 Spring 源码环境首先要安装 GitHub 以及 Gradle. 安装 GitHub Windows 系统对应的 GitHub 版本下载地址为: http://windows.github.com/.如图所示:

Spring + SpringMVC + Druid + JPA(Hibernate impl) 给你一个稳妥的后端解决方案

最近手头的工作不太繁重,自己试着倒腾了一套用开源框架组建的 JavaWeb 后端解决方案. 感觉还不错的样子,但实践和项目实战还是有很大的落差,这里只做抛砖引玉之用. 项目 git 地址:https://git.oschina.net/LanboEx/sdh.git 大体采用的开源项目有:Spring + SpringMVC + Druid + JPA(Hibernate Impl). 1. 采用到的开源项目漫谈 Spring 迷人的依赖注入特性, 使其已经稳稳的占据在 JavaEE 项目引用开

SpringMVC,Spring,Hibernate,Mybatis架构开发搭建之SpringMVC部分

辞职待业青年就是有很多时间来写博客,以前在传统行业技术强度相对不大,不处理大数据,也不弄高并发的,所以学不到什么高端编程技术和架构方法,那么我自己就琢磨搞一个SSH架构的东西出来,希望可以帮助到一些朋友,也希望大拿给出相应的指导意见. 先从用了什么东西说起吧 SSHM=SpringMVC+Spring+Hibernate+Mybatis,至于为什么要这么搞,我先简要的说下. SpringMVC 我最初的想法就是,它比struts2小,属于轻量级的MVC框架,而且和spring可以完美结合在一起.

spring+springMVC+JPA配置详解

SpringMVC是越来越火,自己也弄一个Spring+SpringMVC+JPA的简单框架. 1.搭建环境. 1)下载Spring3.1.2的发布包:Hibernate4.1.7的发布包(没有使用hibernate的API,只是使用了它对JPA的实现):下载 BoneCP 连接池框架及其依赖的jar,下载缓存框架ehcache,全部所用到的jar包如下: ? antlr-2.7.7.jar bonecp-0.7.1.RELEASE.jar bonecp-provider-0.7.1-rc2.j

Maven搭建Spring+Struts2+Hibernate项目详解

前言 这篇主要采用Maven搭建Spring+Struts2+Hibernate的整合项目,复习一下SSH框架,虽然spring提供自己的MVC框架,但是Spring也提供和其他框架的无缝整合,采用组件形式对个框架进行管理,项目实例是按照真实企业里面的开发搭建,也是web的最后一片了.数据库使用mysql,连接池使用的是Druid数据源(这些都无关紧要,可以随时的替换),下面就将详细的介绍一下Maven搭建Spring,Struts2,和hibernation的步奏. 1.数据库设计 数据库库表

Spring Boot + Jpa(Hibernate) 架构基本配置

本文转载自:https://blog.csdn.net/javahighness/article/details/53055149 1.基于springboot-1.4.0.RELEASE版本测试 2.springBoot + Hibernate + Druid + Mysql + servlet(jsp) 不废话,直接上代码 一.maven的pom文件 <?xml version="1.0" encoding="UTF-8"?> <project

Spring Boot整合Spring MVC、Spring、Spring Data JPA(Hibernate)

一句话总结:Spring Boot不是新的功能框架,而是为了简化如SSH.SSM等等多个框架的搭建.整合及配置.使用Spring Boot 10分钟搭建起Spring MVC.Spring.Spring Data JPA(Hibernate)基础后台架构.基本零配置,全注解. 步骤一: 使用Spring Boot提供的网站生成maven项目及基础依赖.打开https://start.spring.io/网站,右侧输入想要的特性依赖.输入Web提供整合Spring MVC,输入JPA提供整合Spr