Commit 282c99b1 authored by 杨伊博's avatar 杨伊博

modify mybatis

parent 24b00248
...@@ -45,11 +45,11 @@ ...@@ -45,11 +45,11 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!--mybatis-->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId> <artifactId>spring-jdbc</artifactId>
</dependency> </dependency>
<!--mybatis-->
<dependency> <dependency>
<groupId>org.mybatis</groupId> <groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId> <artifactId>mybatis</artifactId>
......
...@@ -16,17 +16,15 @@ ...@@ -16,17 +16,15 @@
<properties> <properties>
<start-class>com.us.Application</start-class> <start-class>com.us.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<mybatis.version>3.2.7</mybatis.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
</properties> </properties>
<dependencies> <dependencies>
<!--springboot--> <!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> <artifactId>spring-boot-starter-security</artifactId>
...@@ -36,11 +34,6 @@ ...@@ -36,11 +34,6 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<!--db--> <!--db-->
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
...@@ -59,6 +52,23 @@ ...@@ -59,6 +52,23 @@
</exclusions> </exclusions>
</dependency> </dependency>
<!--mybatis-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
package com.us.example.config;
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;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* Created by yangyibo on 17/1/18.
*/
@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.domain");
factory.setDataSource(dataSource);
Map<String, Object> jpaProperties = new HashMap<>();
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;
}
}
package com.us.example.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
@ComponentScan
public class MyBatisConfig {
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
// sessionFactory.setPlugins(new Interceptor[]{new PageInterceptor()});
sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:mapper/*.xml"));
return sessionFactory;
}
}
package com.us.example.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//@Retention: 定义注解的保留策略,注释类型的注释要保留
@Retention(RetentionPolicy.RUNTIME)
//@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。
//作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
//取值(ElementType)有:
//CONSTRUCTOR:用于描述构造器
//2.FIELD:用于描述域
//3.LOCAL_VARIABLE:用于描述局部变量
//4.METHOD:用于描述方法
//5.PACKAGE:用于描述包
//6.PARAMETER:用于描述参数
//7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
@Target(ElementType.TYPE)
public @interface MyBatisRepository {
}
package com.us.example.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisScannerConfig {
@Bean
public MapperScannerConfigurer MapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.us.example.dao");
mapperScannerConfigurer.setAnnotationClass(MyBatisRepository.class);
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
package com.us.example.config;
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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
@Configuration
@ComponentScan
public class TransactionConfig implements TransactionManagementConfigurer{
@Autowired
private DataSource dataSource;
@Bean(name = "transactionManager")
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
\ No newline at end of file
...@@ -14,27 +14,27 @@ import org.springframework.security.core.userdetails.UserDetailsService; ...@@ -14,27 +14,27 @@ import org.springframework.security.core.userdetails.UserDetailsService;
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean @Bean
UserDetailsService customUserService(){ //2 UserDetailsService customUserService(){ //注册UserDetailsService 的bean
return new CustomUserService(); return new CustomUserService();
} }
@Override @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()); //3 auth.userDetailsService(customUserService()); //user Details Service验证
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() http.authorizeRequests()
.anyRequest().authenticated() //4 .anyRequest().authenticated() //任何请求,登录后可以访问
.and() .and()
.formLogin() .formLogin()
.loginPage("/login") .loginPage("/login")
.failureUrl("/login?error") .failureUrl("/login?error")
.permitAll() //5 .permitAll() //登录页面用户任意访问
.and() .and()
.logout().permitAll(); //6 .logout().permitAll(); //注销行为任意访问
} }
......
package com.us.example.dao;
import com.us.example.domain.SysRole;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by yangyibo on 17/1/18.
*/
public interface SysRoleRepositiory extends JpaRepository<SysRole,Integer> {
SysRole findById(Integer id);
}
package com.us.example.dao;
import com.us.example.domain.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by yangyibo on 17/1/18.
*/
public interface SysUserRepository extends JpaRepository<SysUser,Long> {
SysUser findByUsername(String username);
}
package com.us.example.dao;
import com.us.example.config.MyBatisRepository;
import com.us.example.domain.SysUser;
@MyBatisRepository
public interface UserDao {
public SysUser findByUserName(String username);
}
package com.us.example.domain; package com.us.example.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/** /**
* Created by yangyibo on 17/1/17. * Created by yangyibo on 17/1/17.
*/ */
@Entity
@Table(name = "Sys_Role")
public class SysRole { public class SysRole {
@Id
@GeneratedValue
private Integer id; private Integer id;
private String name; private String name;
public Integer getId() { public Integer getId() {
......
package com.us.example.domain; package com.us.example.domain;
import java.util.List;
import javax.persistence.*;
/** /**
* Created by yangyibo on 17/1/17. * Created by yangyibo on 17/1/17.
*/ */
@Entity
@Table(name = "Sys_User")
public class SysUser { //用户实体实现UserDetails接口,我门的用户实体即位 security 所使用的用户 public class SysUser { //用户实体实现UserDetails接口,我门的用户实体即位 security 所使用的用户
private Integer id;
@Id
@GeneratedValue
private Long id;
private String username; private String username;
private String password; private String password;
private Integer role_id;
public Long getId() { private List<SysRole> roles;
public Integer getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
...@@ -42,13 +37,12 @@ public class SysUser { //用户实体实现UserDetails接口,我门的用户实 ...@@ -42,13 +37,12 @@ public class SysUser { //用户实体实现UserDetails接口,我门的用户实
this.password = password; this.password = password;
} }
public List<SysRole> getRoles() {
public Integer getRole_id() { return roles;
return role_id;
} }
public void setRole_id(Integer role_id) { public void setRoles(List<SysRole> roles) {
this.role_id = role_id; this.roles = roles;
} }
} }
package com.us.example.security; package com.us.example.security;
import com.us.example.dao.SysRoleRepositiory; import com.us.example.dao.UserDao;
import com.us.example.dao.SysUserRepository; import com.us.example.domain.SysRole;
import com.us.example.domain.SysUser; import com.us.example.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
...@@ -17,24 +17,25 @@ import java.util.List; ...@@ -17,24 +17,25 @@ import java.util.List;
* Created by yangyibo on 17/1/18. * Created by yangyibo on 17/1/18.
*/ */
@Service @Service
public class CustomUserService implements UserDetailsService { //1 public class CustomUserService implements UserDetailsService { //自定义UserDetailsService 接口
@Autowired
SysUserRepository userRepository;
@Autowired @Autowired
SysRoleRepositiory sysRoleRepositiory; UserDao userDao;
@Override @Override
public UserDetails loadUserByUsername(String username) { //2 public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户
SysUser user = userRepository.findByUsername(username); SysUser user = userDao.findByUserName(username);
if(user == null){ if(user == null){
throw new UsernameNotFoundException("用户名不存在"); throw new UsernameNotFoundException("用户名不存在");
} }
List<SimpleGrantedAuthority> authorities = new ArrayList<>(); List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。 //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
authorities.add(new SimpleGrantedAuthority(sysRoleRepositiory.findById(user.getRole_id()).getName())); for(SysRole role:user.getRoles())
{
authorities.add(new SimpleGrantedAuthority(role.getName()));
System.out.println(role.getName());
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(), authorities); user.getPassword(), authorities);
......
...@@ -7,5 +7,3 @@ ms.db.maxActive=500 ...@@ -7,5 +7,3 @@ ms.db.maxActive=500
logging.level.org.springframework.security= INFO logging.level.org.springframework.security= INFO
spring.thymeleaf.cache=false spring.thymeleaf.cache=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.us.example.dao.UserDao">
<resultMap id="userMap" type="com.us.example.domain.SysUser">
<id property="id" column="ID"/>
<result property="username" column="username"/>
<result property="password" column="PASSWORD"/>
<collection property="roles" ofType="com.us.example.domain.SysRole">
<result column="name" property="name"/>
</collection>
</resultMap>
<select id="findByUserName" parameterType="String" resultMap="userMap">
select u.*
,r.name
from Sys_User u
LEFT JOIN sys_role_user sru on u.id= sru.Sys_User_id
LEFT JOIN Sys_Role r on sru.Sys_Role_id=r.id
where username= #{username}
</select>
</mapper>
\ 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