Commit 5a3a1f69 authored by 杨伊博's avatar 杨伊博

springboot-jpa is ok

parent afbb0a97
<?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>
<groupId>com.us</groupId>
<artifactId>springboot-jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<start-class>com.us.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<!-- springboot -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--util-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.us.example;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import static org.springframework.boot.SpringApplication.run;
/**
* Created by yangyibo on 17/1/17.
*/
@ComponentScan(basePackages ="com.us.example")
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
\ No newline at end of file
package com.us.example.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name = "sec_user")
public class User {
@Id
@GeneratedValue
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
@Column(name = "username")
private String username;
@Column(name = "division_id")
private Integer divisionId;
@Column(name = "email")
private String email;
@Column(name = "gender")
private String gender;
@Column(name = "mobilephone")
private String mobilephone;
@Column(name = "telephone")
private String telephone;
@Column(name = "user_type")
private Integer userType;
@Column(name = "create_by")
private String createBy;
@Column(name = "create_time")
private Date createTime;
@Column(name = "update_by")
private String updateBy;
@Column(name = "update_time")
private Date updateTime;
@Column(name = "disabled")
private Integer disabled;
@Column(name = "theme")
private String theme;
@Column(name = "is_ldap")
private Integer isLdap;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getDivisionId() {
return divisionId;
}
public void setDivisionId(Integer divisionId) {
this.divisionId = divisionId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisabled() {
return disabled;
}
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public Integer getIsLdap() {
return isLdap;
}
public void setIsLdap(Integer isLdap) {
this.isLdap = isLdap;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
\ No newline at end of file
package com.us.example.config;
import java.beans.PropertyVetoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
public class DBConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
public ComboPooledDataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("ms.db.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("ms.db.url"));
dataSource.setUser(env.getProperty("ms.db.username"));
dataSource.setPassword(env.getProperty("ms.db.password"));
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(5);
dataSource.setInitialPoolSize(10);
dataSource.setMaxIdleTime(300);
dataSource.setAcquireIncrement(5);
dataSource.setIdleConnectionTestPeriod(60);
return dataSource;
}
}
\ No newline at end of file
package com.us.example.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories("com.us.example.dao")
@EnableTransactionManagement
@ComponentScan
public class JpaConfig {
@Autowired
private DataSource dataSource;
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
//vendorAdapter.setShowSql(true);
//vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.us.example.bean");
factory.setDataSource(dataSource);
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
jpaProperties.put("hibernate.jdbc.batch_size",50);
//jpaProperties.put("hibernate.show_sql",true);
factory.setJpaPropertyMap(jpaProperties);
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
\ No newline at end of file
package com.us.example.controller;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.us.example.service.UserService;
import com.us.example.util.CommonUtil;
@Controller
@RequestMapping(value = "/users")
public class UserController {
private static final Logger logger = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
/**
* 通过spring data jpa 调用方法
* api :localhost:8099/users/byname?username=xxx
* @param request
* @return
*/
@RequestMapping(value = "/byname", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> getUser(HttpServletRequest request) {
Map<String, Object> map = CommonUtil.getParameterMap(request);
String username = (String) map.get("username");
return new ResponseEntity<>(userService.getUserByName(username), HttpStatus.OK);
}
}
\ No newline at end of file
package com.us.example.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.us.example.bean.User;
/**
* The Interface UserJpaDao.
* @author abel
*/
public interface UserJpaDao extends JpaRepository<User, Long> {
/**
* Find by name.
*
* @param name the name
* @return the user
*/
User findByName(String name);
}
\ No newline at end of file
package com.us.example.service;
import java.util.Map;
import com.us.example.bean.User;
/**
* The Interface UserService.
*/
public interface UserService {
/**
* Gets the user by name.
*
* @param username the user name
* @return the user by name
*/
public User getUserByName(String username);
}
package com.us.example.serviceImpl;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.us.example.dao.UserJpaDao;
import com.us.example.bean.User;
import com.us.example.service.UserService;
/**
*
* @ClassName UserServiceImpl
* @author abel
* @date 2016年11月10日
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserJpaDao userJpaDao;
/**
*
* @param username
* @return
*/
@Override
public User getUserByName(String username) {
return userJpaDao.findByName(username);
}
}
package com.us.example.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
public class CommonUtil {
/**
* 从request中获得参数Map,并返回可读的Map.
*
* @param request the request
* @return the parameter map
*/
public static Map<String, Object> getParameterMap(HttpServletRequest request) {
// 参数Map
Map<String, String[]> properties = request.getParameterMap();
//返回值Map
Map<String, Object> returnMap = new HashMap<String, Object>();
Set<String> keySet = properties.keySet();
for(String key: keySet){
String[] values = properties.get(key);
String value = "";
if(values != null && (values.length==1&&StringUtils.isNotBlank(values[0]))?true:false){
for(int i=0;i<values.length;i++){
if(values[i] != null && !"".equals(values[i])){
// value = new String(values[i].getBytes("ISO-8859-1"),"UTF-8") + ",";
value += values[i] + ",";
}
}
if(value != null && !"".equals(value)){
value = value.substring(0, value.length()-1);
}
if(key.equals("keywords")){//关键字特殊查询字符转义
value = value.replace("_", "\\_").replace("%", "\\%");
}
returnMap.put(key, value);
}
}
return returnMap;
}
}
\ No newline at end of file
server.port=8099
ms.db.driverClassName=com.mysql.jdbc.Driver
ms.db.url=jdbc:mysql://localhost:3306/msm?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&allowMultiQueries=true
ms.db.username=root
ms.db.password=admin
ms.db.maxActive=500
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment