Spring boot权限表设计,启动spring boot会自动生成user_role的表.

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.hackteam.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Entity
@Table(name="user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length=50,nullable=false)
private String username;
private String password;
// 解决传过来的json字段不全,如{"username":"15","password":"888","roleList":[{"name":"administrator"},{"name":"guest"}]}中role缺少id字段
// 导致transientObject Exception异常,加上cascade={CascadeType.ALL}
@ManyToMany(cascade={CascadeType.ALL},fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns={@JoinColumn(name="user_id")}, inverseJoinColumns = {@JoinColumn(name="roles_id")})
private List<Role> roleList;
//set get 方法
}

Role.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.hackteam.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name="role")
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length=50,nullable=false)
private String name;
//set get 方法
}

Dao

1
2
3
4
5
6
7
package com.hackteam.dao;
import com.hackteam.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository<User, Integer> {
}

service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.hackteam.service;
import com.hackteam.dao.UserDao;
import com.hackteam.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
@Transactional
public class UserService {
@Autowired
private UserDao userDao;
public Optional<User> findUserById(Integer id){
return userDao.findById(id);
}
public User SaveUser(User user){
return userDao.save(user);
}
}

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public Optional<User> findUserById(@PathVariable("id") Integer id){
return userService.findUserById(id);
}
@RequestMapping(value = "/user/save",method = RequestMethod.POST)
public User saveUser(@RequestBody User u){
User user = new User();
user.setUsername(u.getUsername());
user.setPassword(u.getPassword());
user.setRoleList(u.getRoleList());
return userService.SaveUser(u);
}

测试添加数据

使用火狐HttpRquester,Post http://127.0.0.1:8081/test/user/save,格式选择application/json.

1
2
3
4
5
6
7
8
9
10
11
12
{
"username": "15",
"password": "888",
"roleList": [
{
"name": "administrator"
},
{
"name": "guest"
}
]
}