纯Java配置SpringMvc整合Spring-Data-JPA

包结构

纯Java配置SpringMvc整合Spring-Data-JPA_第1张图片

WebInitializer.java

package com.niugang;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * 相当于web.xml
 * AbstractAnnotationConfigDispatcherServletInitializer 源码里面有解释
 * 这个是注解形式注册
 * DispatcherServlet容器
 * @author niugang
 *

 */

public class WebInitializer  extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * 源码里面与对此方法的解释 配置applicationContext
     */
@Override
protected Class[] getRootConfigClasses() {//指定上下文配置类

return  new Class[]{RootConfig.class};
}
@Override
protected Class[] getServletConfigClasses() {//指定sprinfgmvc配置类
return new Class[]{SpringMVCconfig.class} ;
}
@Override
protected String[] getServletMappings() { 

return new String[]{"/"}; //将DispatcherServlet请求映射的/上
}

}

SpringMVCconfig.java

package com.niugang;
import javax.servlet.ServletContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import freemarker.cache.WebappTemplateLoader;


/**
 * 
 * @author niugang springmvc java配置文件
 */
@Configuration // 说明此类为配置文件类
@EnableWebMvc // 开启springmvc
@ComponentScan("com.niugang") // 组件扫描

public class SpringMVCconfig extends WebMvcConfigurerAdapter {

/**
* freemaker作为视图解析器
* 
* @return
*/
@Bean
public FreeMarkerViewResolver viewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setContentType("text/html;charset=utf-8");
/*
* 如果注释 resolver.setPrefix("/WEB-INF/views/");
* 下面config需要tplCfg.setTemplateLoader(new
* WebappTemplateLoader(servletContext,"/WEB-INF/views/"));
*/
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setViewClass(FreeMarkerView.class);
return resolver;

}

 /**
     * 配置freemarker
     * @param servletContext
     * @return
     */
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer(ServletContext servletContext) {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
@SuppressWarnings("deprecation")
freemarker.template.Configuration tplCfg = new freemarker.template.Configuration();
tplCfg.setDefaultEncoding("UTF-8");
tplCfg.setTemplateLoader(new WebappTemplateLoader(servletContext));
freeMarkerConfigurer.setConfiguration(tplCfg);
return freeMarkerConfigurer;
}


/**
* 配置静态资源的处理 对静态资源的请求转发到容器缺省的servlet,而不使用DispatcherServlet
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

}

RootConfig.java

package com.niugang;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
 * 上下文配置
 * @author niugang
 *
 */
@Configuration
@ComponentScan(basePackages={"con.niugang"}, 
    excludeFilters={
        @Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)
    }
)
//在上下文中引入jdbc配置文件
@Import({JdbcConfig.class,JPAConfig.class,TransactionalConfig.class})
public class RootConfig {

}

TransactionalConfig.java

package com.niugang;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;


/**
 * 事务配置文件
 * 
 * @author niugang
 *
 */
@Configuration
@EnableTransactionManagement
/*
 * 事务具体配置可以参考 @EnableTransactionManagement里面源码的配置
 */
public class TransactionalConfig {

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory localContainerEntityManagerFactoryBean) {

JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(localContainerEntityManagerFactoryBean);
return txManager;
}

}

JPAConfig.java

package com.niugang;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;


@Configuration
@EnableJpaRepositories
public class JPAConfig {


@Bean

public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {

        // 设置是否生成DDL被已经被初始化后,创建/更新所有相关表
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();


// vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
// 扫描实体类所在包的
factory.setPackagesToScan("com.niugang.entity");
// factory.setEntityManagerFactoryInterface(EntityManagerFactory.class);
factory.setDataSource(dataSource);

return factory;
}


}

JdbcConfig.java

package com.niugang;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
 * jdbc配置文件
 * @author niugang
 *
 */
@Configuration
/*
 * 
 * @PropertySource注解如何使用,源码里面有例子
 * 即从配置文件中如何获取获取值,源码里面也有解释
 *
 */
@PropertySource("classpath:jdbc.properties") 

public class JdbcConfig {

 @Autowired
private Environment env;
/**
* 配置数据源
* @return
*/
@Bean
public DataSource  dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getProperty("url"));
dataSource.setDriverClassName(env.getProperty("driverName"));
dataSource.setUsername(env.getProperty("datausername"));
        dataSource.setPassword(env.getProperty("password"));
return dataSource;
}

}

entity

package com.niugang.entity;


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

//javax.persistence.Entity
@Entity
@Table(name="user")
public class User {
/**
*mysql 自定生成主键
*指示持久性提供者必须分配使用数据库标识列的实体的主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)  
@Column(name="id" ,insertable=false,updatable=false)

private Integer id;

       /**
* @Column中的name默认和字段名相同
*/
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
@Column(name = "phone")
private String phone;
@Column(name = "password")
private String password;


public String getPassword() {
return password;
}


public void setPassword(String password) {
this.password = password;
}


public Integer getId() {
return id;
}


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


public String getName() {
return name;
}


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


public Integer getAge() {
return age;
}


public void setAge(Integer age) {
this.age = age;
}


public String getPhone() {
return phone;
}


public void setPhone(String phone) {
this.phone = phone;
}


}

dao

package com.niugang.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.niugang.entity.User;
/**
 * JpaRepository springboot已经自动配置了,也已经注入数据源了
 * @author niugang
 *
 */
@Repository
public interface UserDao extends JpaRepository {


 


}

service

package com.niugang.service;


import java.util.List;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import com.niugang.dao.UserDao;
import com.niugang.entity.User;


@Service
public class UserService {
@Resource
private UserDao userDao;


/**
* 查询全部
* 
* @return
*/
public List queryList() {
return userDao.findAll();

}

    /**
* 保存
* 
* @param user
*/
@Transactional
public void save(User user) {
userDao.save(user);
throw new RuntimeException("添加数据错误");


}
/**
* 添加对象集合
* @param users
*/
public void save(Iterable users) {
userDao.save(users);


}


/**
* 根据id查询
* 
* @param id
* @return
*/
public User get(int id) {
return userDao.getOne(id);

}

     /**
* 删除
* 
* @param id
*/
public void delete(int id) {
userDao.delete(id);
}
/**
* page分页查询
* @return
*/
public Page queryForPage(Integer page) {
/**
* PageRequest page起始页从0开始
*/
PageRequest pageRequest = null;
if (page== null) {
pageRequest = new PageRequest(0, 4);
} else {
pageRequest = new PageRequest((page-1), 4);
}
     
Page findAll = userDao.findAll(pageRequest);
return findAll;
}

/**
* 不分页排序查询
* @return
*/
public List queryForSort(){
Order idOrder = new Order(Direction.DESC, "id"); 
/*List orders =new ArrayList();
orders.add(idOrder);*/
return userDao.findAll(new Sort(idOrder));
}
}

controller

package com.niugang.controller;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.niugang.entity.User;
import com.niugang.service.UserService;

/**
 * 
 * @author niugang spring boot helloWrold
 */
@Controller
public class IndexController {
@Resource
private UserService userService;

@RequestMapping(value = "/")
public String toIndex(){
return "redirect:index";

}

/**
* 跳转到登录页面
* 
* @param map
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String toLogin(ModelMap map) {
return "login";
}


/**
* 登录信息校验
* 
* @param map
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(ModelMap map, String name,String password) {


if (StringUtils.isNotBlank(name)&& !name.equals("admin") && StringUtils.isNotBlank(password)
&& !password.equals("123456")) {
map.put("errorMessage", "用户名或密码错误");
return "login";
}


return "redirect:index";
}


/**
* 跳转到index页面
* 
* @return
*/
@RequestMapping(value = "/index")
public String index(ModelMap map) {
List list = userService.queryList();
map.put("users", list);
return "index";

}

    /**
* 详情页面
* @param id
* @param map
* @return
*/
@RequestMapping(value = "/detail/{id}")
public String detail(@PathVariable(value="id") Integer id,ModelMap map){
User user = userService.get(id);
map.put("user", user);
return "detail";
}
/**
* 删除
* @param id
* @return
*/
@RequestMapping(value = "/delete/{id}")
public String delete(@PathVariable(value="id") Integer id){
userService.delete(id);
return "redirect:/index";
}
/**
* 跳转到添加页面
* @param map
* @return

*/

      @RequestMapping(value = "/save",method = RequestMethod.GET)
public String toSave(ModelMap map) {
return "add";
}
/**
* 保存添加信息
* @param user
* @return
*/
@RequestMapping(value = "/save",method = RequestMethod.POST)
public String save(User user,ModelMap map){
if(StringUtils.isBlank(user.getName())){
map.put("error", "用户名不能为空");
return "add";
}
if(user.getAge()==null){
map.put("error", "非法年龄");
return "add";
}
if(StringUtils.isBlank(user.getPhone())){
map.put("error", "手机号不能为空");
return "add";
}
user.setPassword("123456");
userService.save(user);
return "redirect:/index";
}
@RequestMapping(value = "/indexPage")
public String indexPage(ModelMap map,Integer page) {
Page queryForPage = userService.queryForPage(page);

map.put("page", queryForPage);
return "index";
}

}

index.html





Insert title here





 
      分页查询

<#if users??> <#list users as user>


   <#if page??> 
   <#list page.content as user>


                        

     
     
     
  
用户名 年龄 电话 操作
${user.name} ${user.age} ${user.phone} 编辑 删除 详情
${user.name} ${user.age} ${user.phone} 编辑 删除 详情
总页数${page.totalPages}当前页面${page.number+1}总记录数${page.totalElements}
    <#if  (page.totalPages gt page.number+1)>            下一页             <#if (page.number !=0)>               上一页                       <#if  (page.totalPages lt page.number+2)>            上一页      

detail.html





Document


  

详情页面

  用户名:   年龄:   电话:

add.html





Document


  

添加

      <#if error??>           ${error}            
           用户名:

            年龄:

            手机号:

                   

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


    ${errorMsg}
    返回


运行结果

纯Java配置SpringMvc整合Spring-Data-JPA_第2张图片

 

纯Java配置SpringMvc整合Spring-Data-JPA_第3张图片

                                                                               微信公众号: 

                                               纯Java配置SpringMvc整合Spring-Data-JPA_第4张图片

                                                                             JAVA程序猿成长之路

                          分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。 

你可能感兴趣的:(spring-data-jpa,spring-mvc,纯Java配置spring环境)