spring data no xml example

This commit is contained in:
sxyx2008
2014-07-22 10:55:21 +08:00
parent d7d3afabb2
commit d4d4a67f01
28 changed files with 4074 additions and 1 deletions
+2 -1
View File
@@ -94,6 +94,8 @@
<module>hibernate-tutorials</module>
<module>commons-dbutils-tutorial</module>
<module>spring-jdbc-tutorials</module>
<module>spring-data-example</module>
<module>spring-ibatis-example</module>
</modules>
<properties>
@@ -417,7 +419,6 @@
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<wtpversion>2.0</wtpversion>
<!-- 增加设置项目encoding的文件 -->
<additionalConfig>
<file>
<name>.settings/org.eclipse.core.resources.prefs</name>
File diff suppressed because it is too large Load Diff
+90
View File
@@ -0,0 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.aimeizi</groupId>
<artifactId>maven-framework-project</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>spring-data-example</artifactId>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.9.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.170</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,102 @@
package net.aimeizi.spring.data.example.config;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.hibernate.ejb.HibernatePersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("net.aimeizi.spring.data.example")
@PropertySource("classpath:application.properties")
@EnableJpaRepositories("net.aimeizi.spring.data.example.repositories")
public class WebConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "jdbc.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "jdbc.password";
private static final String PROPERTY_NAME_DATABASE_URL = "jdbc.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "jdbc.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
@Resource
private Environment env;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setJpaProperties(hibProperties());
return entityManagerFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL));
return properties;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename(env.getRequiredProperty("message.source.basename"));
source.setUseCodeAsDefaultMessage(true);
return source;
}
}
@@ -0,0 +1,42 @@
package net.aimeizi.spring.data.example.config;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(WebConfig.class);
servletContext.addListener(new ContextLoaderListener(applicationContext));
applicationContext.setServletContext(servletContext);
FilterRegistration.Dynamic filter = servletContext.addFilter("characterEncodingFilter", org.springframework.web.filter.CharacterEncodingFilter.class);
filter.setInitParameter("encoding", "utf-8");
filter.setInitParameter("forceEncoding", "true");
filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(applicationContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
@@ -0,0 +1,110 @@
package net.aimeizi.spring.data.example.controller;
import java.util.List;
import javax.validation.Valid;
import net.aimeizi.spring.data.example.entities.Emp;
import net.aimeizi.spring.data.example.exception.EmpNotFound;
import net.aimeizi.spring.data.example.service.EmpService;
import net.aimeizi.spring.data.example.validation.EmpValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/emp")
public class EmpController {
@Autowired
private EmpService empService;
// @Autowired
// private EmpValidator empValidator;
// @InitBinder
// private void initBinder(WebDataBinder binder) {
// binder.setValidator(empValidator);
// }
@RequestMapping(value="/create", method=RequestMethod.GET)
public ModelAndView newEmpPage() {
ModelAndView mav = new ModelAndView("emp-new", "emp", new Emp());
return mav;
}
@RequestMapping(value="/create", method=RequestMethod.POST)
public ModelAndView createNewEmp(@ModelAttribute @Valid Emp emp,
BindingResult result,
final RedirectAttributes redirectAttributes) {
if (result.hasErrors())
return new ModelAndView("emp-new");
ModelAndView mav = new ModelAndView();
String message = "New emp "+emp.getEmpname()+" was successfully created.";
empService.save(emp);
mav.setViewName("redirect:/index.html");
redirectAttributes.addFlashAttribute("message", message);
return mav;
}
@RequestMapping(value="/list", method=RequestMethod.GET)
public ModelAndView empListPage() {
ModelAndView mav = new ModelAndView("emp-list");
List<Emp> empList = empService.find();
mav.addObject("empList", empList);
return mav;
}
@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
public ModelAndView editEmpPage(@PathVariable Integer id) {
ModelAndView mav = new ModelAndView("emp-edit");
Emp emp = empService.findOne(id);
mav.addObject("emp", emp);
return mav;
}
@RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public ModelAndView editEmp(@ModelAttribute @Valid Emp emp,
BindingResult result,
@PathVariable Integer id,
final RedirectAttributes redirectAttributes) throws EmpNotFound {
emp.setEmpid(id);
if (result.hasErrors())
return new ModelAndView("emp-edit");
ModelAndView mav = new ModelAndView("redirect:/index.html");
String message = "Emp was successfully updated.";
empService.update(emp);
redirectAttributes.addFlashAttribute("message", message);
return mav;
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView deleteEmp(@PathVariable Integer id,
final RedirectAttributes redirectAttributes) throws EmpNotFound {
ModelAndView mav = new ModelAndView("redirect:/index.html");
Emp emp = empService.delete(empService.findOne(id));
String message = "The emp "+emp.getEmpname()+" was successfully deleted.";
redirectAttributes.addFlashAttribute("message", message);
return mav;
}
}
@@ -0,0 +1,14 @@
package net.aimeizi.spring.data.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WelcomeController {
@RequestMapping("index")
public String index(){
return "index";
}
}
@@ -0,0 +1,62 @@
package net.aimeizi.spring.data.example.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table
public class Dept {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int deptid;
private String deptname;
private String deptphonenumber;
@OneToMany(mappedBy="dept",cascade=CascadeType.ALL)
private Set<Emp> emps = new HashSet<Emp>();
public int getDeptid() {
return deptid;
}
public void setDeptid(int deptid) {
this.deptid = deptid;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getDeptphonenumber() {
return deptphonenumber;
}
public void setDeptphonenumber(String deptphonenumber) {
this.deptphonenumber = deptphonenumber;
}
public Set<Emp> getEmps() {
return emps;
}
public void setEmps(Set<Emp> emps) {
this.emps = emps;
}
}
@@ -0,0 +1,69 @@
package net.aimeizi.spring.data.example.entities;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table
public class Emp {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int empid;
@NotEmpty(message="please enter your emp empname.")
@Size(min=6,max=16,message="empname长度在6~16个字符之间.")
private String empname;
@Email
@NotEmpty
private String empaddress;
@ManyToOne(cascade={CascadeType.REFRESH,CascadeType.REMOVE,CascadeType.MERGE})
@JoinColumn(name="deptid")
private Dept dept;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpaddress() {
return empaddress;
}
public void setEmpaddress(String empaddress) {
this.empaddress = empaddress;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}
@@ -0,0 +1,57 @@
package net.aimeizi.spring.data.example.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="POST")
public class Post {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="POST_ID")
Integer postId;
@Column(name="TITLE")
String title;
@Column(name="POST_DATE")
Date postDate;
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getPostDate() {
return postDate;
}
public void setPostDate(Date postDate) {
this.postDate = postDate;
}
@Override
public String toString() {
return "Post [postId=" + postId + ", title=" + title + ", postDate="
+ postDate + "]";
}
}
@@ -0,0 +1,5 @@
package net.aimeizi.spring.data.example.exception;
public class EmpNotFound extends Exception{
}
@@ -0,0 +1,9 @@
package net.aimeizi.spring.data.example.repositories;
import net.aimeizi.spring.data.example.entities.Emp;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmpRepository extends JpaRepository<Emp, Integer> {
}
@@ -0,0 +1,9 @@
package net.aimeizi.spring.data.example.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import net.aimeizi.spring.data.example.entities.Post;
public interface PostRepository extends JpaRepository<Post, Integer> {
}
@@ -0,0 +1,19 @@
package net.aimeizi.spring.data.example.service;
import java.util.List;
import net.aimeizi.spring.data.example.entities.Emp;
public interface EmpService {
List<Emp> find();
Emp findOne(int id);
Emp save(Emp emp);
Emp update(Emp emp);
Emp delete(Emp emp);
}
@@ -0,0 +1,18 @@
package net.aimeizi.spring.data.example.service;
import java.util.List;
import net.aimeizi.spring.data.example.entities.Post;
public interface PostService {
List<Post> find();
Post findOne(int id);
Post save(Post post);
Post update(Post post);
Post delete(Post post);
}
@@ -0,0 +1,59 @@
package net.aimeizi.spring.data.example.service.impl;
import java.util.List;
import net.aimeizi.spring.data.example.entities.Emp;
import net.aimeizi.spring.data.example.repositories.EmpRepository;
import net.aimeizi.spring.data.example.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpRepository empRepository;
@Override
public List<Emp> find() {
return empRepository.findAll();
}
@Override
public Emp findOne(int id) {
return empRepository.findOne(id);
}
@Override
public Emp save(Emp emp) {
return empRepository.save(emp);
}
@Override
public Emp update(Emp emp) {
Emp one = empRepository.findOne(emp.getEmpid());
one.setEmpname(emp.getEmpname());
one.setEmpaddress(emp.getEmpaddress());
one.setDept(emp.getDept());
return one;
}
@Override
public Emp delete(Emp emp) {
Emp one = empRepository.findOne(emp.getEmpid());
empRepository.delete(one);
return one;
}
}
@@ -0,0 +1,57 @@
package net.aimeizi.spring.data.example.service.impl;
import java.util.List;
import net.aimeizi.spring.data.example.entities.Post;
import net.aimeizi.spring.data.example.repositories.PostRepository;
import net.aimeizi.spring.data.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class PostServiceImpl implements PostService {
@Autowired
PostRepository repository;
@Override
public List<Post> find() {
return repository.findAll();
}
@Override
public Post save(Post post) {
return repository.save(post);
}
@Override
public Post update(Post post) {
Post one = repository.findOne(post.getPostId());
one.setTitle(post.getTitle());
one.setPostDate(post.getPostDate());
return one;
}
@Override
public Post delete(Post post) {
Post one = repository.findOne(post.getPostId());
repository.delete(one);
return one;
}
@Override
public Post findOne(int id) {
return repository.findOne(id);
}
}
@@ -0,0 +1,24 @@
package net.aimeizi.spring.data.example.validation;
import net.aimeizi.spring.data.example.entities.Emp;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class EmpValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Emp.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "empname", "emp.empname.empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "empaddress", "emp.empaddress.empty");
}
}
@@ -0,0 +1,13 @@
message.source.basename=i18n/messages
#jdbc properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/to_thought_tutorial
jdbc.username=root
jdbc.password=
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
entitymanager.packages.to.scan=net.aimeizi.spring.data.example.entities
@@ -0,0 +1,2 @@
emp.empname.empty = The "emp empname" field can't be empty.
emp.empaddress.empty = The "emp empaddress" field can't be empty.
@@ -0,0 +1,6 @@
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.conversionPattern=%-5p - %-26.26c{1} - %m\n
log4j.rootLogger=INFO,Stdout
log4j.logger.org.springframework=INFO
@@ -0,0 +1,34 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit Emp page</title>
</head>
<body>
<h1>Edit Emp page</h1>
<form:form method="POST" commandName="emp" action="${pageContext.request.contextPath}/emp/edit/${emp.empid}.html" >
<table>
<tbody>
<tr>
<td>Emp name:</td>
<td><form:input path="empname" /></td>
<td><form:errors path="empname" cssStyle="color: red;"/></td>
</tr>
<tr>
<td>Emp empaddress:</td>
<td><form:input path="empaddress" /></td>
<td><form:errors path="empaddress" cssStyle="color: red;"/></td>
</tr>
<tr>
<td><input type="submit" value="Create" /></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
<a href="${pageContext.request.contextPath}/index">Home page</a>
</body>
</html>
@@ -0,0 +1,33 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Emp List page</title>
</head>
<body>
<h1>Emp List page</h1>
<table style="text-align: center;" border="1px" cellpadding="0" cellspacing="0" >
<thead>
<tr>
<th width="25px">id</th><th width="150px">company</th><th width="25px">employees</th><th width="50px">actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="emp" items="${empList}">
<tr>
<td>${emp.empid}</td>
<td>${emp.empname}</td>
<td>${emp.empaddress}</td>
<td>
<a href="${pageContext.request.contextPath}/emp/edit/${emp.empid}.html">Edit</a><br/>
<a href="${pageContext.request.contextPath}/emp/delete/${emp.empid}.html">Delete</a><br/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<a href="${pageContext.request.contextPath}/index">Home page</a>
</body>
</html>
@@ -0,0 +1,34 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Emp page</title>
</head>
<body>
<h1>New Emp page</h1>
<form:form method="POST" commandName="emp" action="${pageContext.request.contextPath}/emp/create.html" >
<table>
<tbody>
<tr>
<td>Emp empname:</td>
<td><form:input path="empname" /></td>
<td><form:errors path="empname" cssStyle="color: red;"/></td>
</tr>
<tr>
<td>Emp empaddress:</td>
<td><form:input path="empaddress" /></td>
<td><form:errors path="empaddress" cssStyle="color: red;"/></td>
</tr>
<tr>
<td><input type="submit" value="Create" /></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
<a href="${pageContext.request.contextPath}/index">Home page</a>
</body>
</html>
@@ -0,0 +1,17 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home page</title>
</head>
<body>
<h1>Home page</h1>
<p>
Welcome to "Emp application".<br/>
<i>${message}</i><br/>
<a href="${pageContext.request.contextPath}/emp/create.html">Create a new emp</a><br/>
<a href="${pageContext.request.contextPath}/emp/list.html">View all emp</a><br/>
</p>
</body>
</html>
@@ -0,0 +1,9 @@
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>spring-data-example</display-name>
</web-app>
@@ -0,0 +1,121 @@
package net.aimeizi.spring.data.example;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import net.aimeizi.spring.data.example.config.WebConfig;
import net.aimeizi.spring.data.example.entities.Dept;
import net.aimeizi.spring.data.example.entities.Emp;
import net.aimeizi.spring.data.example.service.EmpService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WebConfig.class)
public class EmpRepositoryTest {
@Autowired
EmpService empService;
private static IndexColorModel createIndexColorModel() {
byte[] r = new byte[ 256 ];
byte[] g = new byte[ 256 ];
byte[] b = new byte[ 256 ];
// now fill in the r,g, and b arrays with a ramp or 0
for ( int i = 0; i < 256 ; i++ ){
r[i] = (byte) i;
g[i] = (byte) i;
b[i] = (byte) i;
}
return new IndexColorModel( 8, 256, r, g, b );
}
@Test
public void save(){
Emp emp = new Emp();
emp.setEmpname("马云");
emp.setEmpaddress("浙江杭州");
Dept dept = new Dept();
dept.setDeptname("研发部");
dept.setDeptphonenumber("110");
emp.setDept(dept);
empService.save(emp );
}
@Test
public void delete(){
Emp emp = empService.findOne(2);
empService.delete(emp);
}
@Test
public void update(){
Emp emp = empService.findOne(5);
emp.setEmpname("马化腾");
emp.setEmpaddress("广东深圳");
Dept dept = emp.getDept();
dept.setDeptphonenumber("120");
dept.setDeptname("大客户服务部");
emp.setDept(dept);
empService.update(emp);
}
@Test
public void imageEmail() throws Exception{
String email = "sxyx2008@163.com";
int height = 22;
BufferedImage bi = new BufferedImage(255, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
Font mFont = new Font("Verdana", Font.PLAIN, 14);
g.setFont(mFont);
g.drawString(email, 2, 19);
FontMetrics fm = g.getFontMetrics();
int new_width = fm.charsWidth(email.toCharArray(), 0, email.length()) + 4;
int new_height = fm.getHeight();
BufferedImage nbi = new BufferedImage(new_width, new_height,
BufferedImage.TYPE_BYTE_INDEXED, createIndexColorModel());
Graphics2D g2 = (Graphics2D) nbi.getGraphics();
g2.setColor(new Color(0, 0, 0, 0));// 透明
g2.fillRect(0, 0, new_width, new_height);
g2.setFont(mFont);
g2.setColor(new Color(200, 0, 0));
g2.drawString(email, 2, new_height - 4);
ImageIO.write(nbi, "gif", new FileOutputStream(
"target/sxyx2008@163.com.gif"));
}
}
@@ -0,0 +1,81 @@
package net.aimeizi.spring.data.example;
import static org.junit.Assert.assertNotNull;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import net.aimeizi.spring.data.example.config.WebConfig;
import net.aimeizi.spring.data.example.entities.Post;
import net.aimeizi.spring.data.example.service.PostService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WebConfig.class,loader=AnnotationConfigContextLoader.class)
public class PostRepositoryTest {
@Autowired
PostService postService;
@Test
public void save() {
Post post = new Post();
post.setPostDate(new Date());
post.setTitle("Second Post");
postService.save(post);
Post dbpost = postService.findOne(post.getPostId());
assertNotNull(dbpost);
System.out.println(dbpost.getTitle());
}
@Test
public void find() {
List<Post> list = postService.find();
for (Post p : list) {
System.out.println(p);
}
}
@Test
public void findOne() {
System.out.println(postService.findOne(1));
}
@Test
public void update(){
Post post = new Post();
post.setPostId(1);
post.setPostDate(Calendar.getInstance().getTime());
post.setTitle("update title");
postService.update(post);
}
@Test
public void delete(){
Post post = postService.findOne(2);
postService.delete(post);
find();
}
}