我是靠谱客的博主 微笑鞋垫,最近开发中收集的这篇文章主要介绍spring+hibernate+maven项目结构搭建 spring+hibernate+maven项目结构搭建 ,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

spring+hibernate+maven项目结构搭建

前面一遍文章中我们讲到了hibernate和ibatis的技术选型问题, 那么可能很多同学都比较喜欢使用ibatis, 但是万一哪天你需要用到hibernate 怎么办呢, 下面我讲带领大家如何搭建零配置的spring+hibernate技术架构, 直接代码吧:

开始之前我先贴一下我的项目结构图如下:


首先配置pom.xml:

<?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:

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文件:

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:

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:

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();
    }
}

其他的都是一下配置和静态文件 过多的就不介绍了, 最后运行后的结果:



整体的代码我就不放在上面, 直接打包提供下载吧 http://download.csdn.net/detail/ch751652064/9471657


转载于:https://my.oschina.net/chenxiaobian/blog/646797

最后

以上就是微笑鞋垫为你收集整理的spring+hibernate+maven项目结构搭建 spring+hibernate+maven项目结构搭建 的全部内容,希望文章能够帮你解决spring+hibernate+maven项目结构搭建 spring+hibernate+maven项目结构搭建 所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(35)

评论列表共有 0 条评论

立即
投稿
返回
顶部