前面一遍文章中咱們講到了hibernate和ibatis的技術選型問題, 那麼可能不少同窗都比較喜歡使用ibatis, 可是萬一哪天你須要用到hibernate 怎麼辦呢, 下面我講帶領你們如何搭建零配置的spring+hibernate技術架構, 直接代碼吧: java
開始以前我先貼一下個人項目結構圖以下: mysql
首先配置pom.xml: git
<?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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>wechatmeal</name> <groupId>com</groupId> <artifactId>wechatmeal</artifactId> <version>1.2-SNAPSHOT</version> <!--Source Control Management--> <scm> <connection>scm:git:git@github.com:xiaobianchen/WeChatMeal.git</connection> <developerConnection>scm:git:git@github.com:xiaobianchen/WeChatMeal.git</developerConnection> <url>https://github.com/xiaobianchen/WeChatMeal.git</url> <tag>HEAD</tag> </scm> <!--developer information--> <developers> <developer> <id>xiaobian chen</id> <name>xiaobian chen</name> <email>chenxiaobian89@163.com</email> </developer> </developers> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.1.7.RELEASE</spring.version> <hibernate.version>4.3.10.Final</hibernate.version> <spring.redis>1.2.1.RELEASE</spring.redis> <spring.quartz>1.8.6</spring.quartz> <mybatis.version>3.2.3</mybatis.version> <mybatis-spring.version>1.2.1</mybatis-spring.version> <spring.mongodb>1.8.2.RELEASE</spring.mongodb> <mysql.driver.version>5.1.13</mysql.driver.version> <project.build.fastjson>1.1.41</project.build.fastjson> <project.build.gson>2.5</project.build.gson> <jstl.version>1.2</jstl.version> <common-io.version>2.4</common-io.version> <common-dbcp.version>1.4</common-dbcp.version> <jstl.version>1.2</jstl.version> <fileupload.version>1.3.1</fileupload.version> <jackson.version>1.9.13</jackson.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.7</slf4j.version> <druid.version>1.0.12</druid.version> <junit.version>4.8.2</junit.version> <servlet.version>2.5</servlet.version> <dubbo.version>2.5.3</dubbo.version> <httpclient.version>4.5</httpclient.version> <commons-httpclient.version>3.1</commons-httpclient.version> <java.version>1.7</java.version> </properties> <dependencies> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> <version>${junit.version}</version> </dependency> <!--spring core--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!--webmvc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--spring web--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!--hibernate--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!--spring context support--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!--spring transaction--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!--dbcp--> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>${common-dbcp.version}</version> </dependency> <!--spring aop--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!--spring-test--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--spring redis--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring.redis}</version> </dependency> <!-- spring quartz--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>${spring.quartz}</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--mybatis-spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!--spring jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>${project.build.gson}</version> </dependency> <!-- alibaba fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${project.build.fastjson}</version> </dependency> <!--mongodb--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>${spring.mongodb}</version> </dependency> <!--jstl--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.3.Final</version> </dependency> <!--commons-io--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${common-io.version}</version> </dependency> <!--fileupload--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileupload.version}</version> </dependency> <!--jackson--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jackson.version}</version> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <!--dubbo--> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>${dubbo.version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> </exclusions> </dependency> <!--httpclient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!--commons-httpclient--> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>${commons-httpclient.version}</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>WeChatMeal</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>WeChatMeal</finalName> </build> </project>
接下來分別是AppConfig: github
package com.config; import com.converter.RoleToUserProfileConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.*") public class AppConfig extends WebMvcConfigurerAdapter{ @Autowired RoleToUserProfileConverter roleToUserProfileConverter; /** * 配置視圖 ViewResolver */ @Override public void configureViewResolvers(ViewResolverRegistry registry) { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); registry.viewResolver(viewResolver); } /** * 配置靜態資源 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); } /** * 配置converter */ @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(roleToUserProfileConverter); } /** * 配置message用於驗證表單 */ @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Override public void configurePathMatch(PathMatchConfigurer matcher) { matcher.setUseRegisteredSuffixPatternMatch(true); } }
AppInitializer.java文件: web
package com.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * @author xiaobianchen * @version 1.0 2016/3/23 */ public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{AppConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
配置HibernateConfiguration.java: redis
package com.config; import com.model.ConfigConstant; 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.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; import javax.annotation.Resource; import javax.sql.DataSource; import java.util.Properties; /** * @author xiaobianchen * @version 1.0 2016/3/23 */ @Configuration @EnableTransactionManagement @ComponentScan({ "com.config" }) @PropertySource(value = { "classpath:jdbc.properties" }) public class HibernateConfiguration { @Resource private Environment env; /** * 配置數據源 */ @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getRequiredProperty(ConfigConstant.DRIVER_NAME)); dataSource.setUrl(env.getRequiredProperty(ConfigConstant.URL)); dataSource.setUsername(env.getRequiredProperty(ConfigConstant.USERNAME)); dataSource.setPassword(env.getRequiredProperty(ConfigConstant.PASSWORD)); return dataSource; } @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource()); sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(ConfigConstant.PACKAGE_SCAN)); sessionFactoryBean.setHibernateProperties(hibProperties()); return sessionFactoryBean; } /** * 配置hibernate */ private Properties hibProperties() { Properties properties = new Properties(); properties.put(ConfigConstant.HIBERNATE_DIALECT, env.getRequiredProperty(ConfigConstant.HIBERNATE_DIALECT)); properties.put(ConfigConstant.HIBERNATE_SHOW_SQL, env.getRequiredProperty(ConfigConstant.HIBERNATE_SHOW_SQL)); properties.put(ConfigConstant.HIBERNATE_FORMAT_SQL, env.getRequiredProperty(ConfigConstant.HIBERNATE_FORMAT_SQL)); return properties; } /** * 配置事務管理 */ @Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); return transactionManager; } }
Controller下的AppController: spring
package com.controller; import com.model.User; import com.model.UserProfile; import com.service.UserProfileService; import com.service.UserService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.util.List; import java.util.Locale; /** * @author xiaobianchen * @version 1.0 2016/3/23 */ @Controller @SessionAttributes("roles") public class AppController { private static final Logger LOG = Logger.getLogger(AppController.class); @Autowired private UserService userService; @Autowired private UserProfileService userProfileService; @Autowired private MessageSource messageSource; /** * 列出全部用戶信息 */ @RequestMapping(value="/list",method = RequestMethod.GET) public ModelAndView listUsers(ModelMap modelMap){ List<User> userList = userService.findAllUsers(); ModelAndView model = new ModelAndView(); model.addObject("userList", userList); model.setViewName("userslist"); return model; } /** * 註冊一個新用戶 */ @RequestMapping(value="/newuser",method = RequestMethod.GET) public String newUser(ModelMap modelMap){ User user = new User(); modelMap.addAttribute("user", user); return "registration"; } /** * 註冊新用戶 */ @RequestMapping(value="/newuser",method = RequestMethod.POST) public String saveUser(@Valid User user,ModelMap modelMap,BindingResult result){ if(result.hasErrors()){ return "registration"; } if (!userService.isUserSSOUnique(user.getId(), user.getSsoId())) { FieldError ssoError = new FieldError("user", "ssoId", messageSource.getMessage("non.unique.sso", new String[]{user.getSsoId()}, Locale.getDefault())); result.addError(ssoError); return "registration"; } userService.save(user); modelMap.addAttribute("success", "User " + user.getFirstName() + " " + user.getLastName() + " register successfully"); return "registraionsuccess"; } /** * 編輯用戶信息 */ @RequestMapping(value="/edit-user/{ssoId}",method = RequestMethod.GET) public String editUser(@PathVariable String ssoId,ModelMap modelMap){ User user = userService.findBySSOId(ssoId); LOG.info("user info:" + user); modelMap.addAttribute("user",user); modelMap.addAttribute("edit", true); return "registration"; } /** * 編輯用戶 * @param ssoId 惟一標識用戶身份 * @param modelMap 存user信息 做用域在request級別 * @param user */ @RequestMapping(value="/edit-user/{ssoId}",method = RequestMethod.POST) public String updateUser(@PathVariable String ssoId,ModelMap modelMap, @Valid User user){ userService.updateUser(user); modelMap.addAttribute("success", "User " + user.getFirstName() + " " + user.getLastName() + " updated successfully"); return "redirect:/list"; } /** * 刪除用戶 * @param ssoId 惟一標識用戶身份 */ @RequestMapping(value="/delete-user/{ssoId}",method = RequestMethod.GET) public String deleteUser(@PathVariable String ssoId){ userService.delete(ssoId); return "redirect:/list"; } @ModelAttribute("roles") public List<UserProfile> initializeProfiles(){ return userProfileService.findAll(); } }
其餘的都是一下配置和靜態文件 過多的就不介紹了, 最後運行後的結果: sql
總體的代碼我就不放在上面, 直接打包提供下載吧 http://download.csdn.net/detail/ch751652064/9471657 mongodb