@Override public User getUserById(String id) { String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id"; Object[] params = {id}; return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id); }
时间: 2024-04-18 22:32:59 浏览: 122
您好!这段代码是一个Java方法,用于根据用户ID从数据库中获取用户信息。它使用了一个SQL查询语句来查找与给定ID匹配的用户记录,并将结果封装到一个User对象中返回。
具体的步骤如下:
1. 构建SQL查询语句,使用占位符(?)来表示参数。
2. 创建一个Object数组,包含了需要传递给查询的参数值(这里只有一个id)。
3. 使用数据库操作模板(template)的queryForObject方法执行查询,将查询结果映射到User对象上,并将参数传递给查询。
4. 返回User对象。
请注意,这段代码只给出了方法的实现部分,并没有提供完整的类定义或数据库操作模板的初始化代码。如果您需要完整的代码,请提供更多相关信息或上下文。
相关问题
@Override public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) { StringBuffer sql = new StringBuffer(); sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id"); List<Object> list = new ArrayList<Object>(); if (!StringUtils.isNullOrEmpty(userName)) { sql.append(" and u.userName like ?"); list.add("%" + userName + "%"); } if (userRole > 0) { sql.append(" and u.userRole = ?"); list.add(userRole); } sql.append(" order by creationDate DESC limit ?,?"); currentPageNo = (currentPageNo - 1) * pageSize; list.add(currentPageNo); list.add(pageSize); Object[] params = list.toArray(); System.out.println("sql ----> " + sql.toString()); return template.query(sql.toString(), new BeanPropertyRowMapper<User>(User.class), params); }
您好!这段代码是一个Java方法,用于从数据库中获取用户列表。它接受一些参数,如用户名、用户角色、当前页码和每页大小,以便进行条件查询和分页查询。
具体的步骤如下:
1. 创建一个StringBuffer对象sql,用于构建SQL查询语句。
2. 使用append方法逐步拼接SQL查询语句,该语句从smbms_user表和smbms_role表中查询用户信息,同时将用户角色的名称也查询出来。
3. 创建一个List对象list,用于存储需要传递给查询的参数值。
4. 如果用户名不为空,将其作为查询条件之一,拼接到SQL语句中,并将参数值添加到list中。
5. 如果用户角色大于0,将其作为查询条件之一,拼接到SQL语句中,并将参数值添加到list中。
6. 添加分页查询的条件,拼接到SQL语句中,并将当前页码和每页大小计算得到的值添加到list中。
7. 将list转换为Object数组params。
8. 打印输出完整的SQL语句。
9. 使用数据库操作模板(template)的query方法执行查询,将查询结果映射到User对象的List集合中,并将参数传递给查询。
10. 返回User对象的List集合。
请注意,这段代码只给出了方法的实现部分,并没有提供完整的类定义或数据库操作模板的初始化代码。如果您需要完整的代码,请提供更多相关信息或上下文。
帮我写一个简单的权限控制项目:springboot+shiro+MyBatis,数据库表1:user(id,username,password),表2:role(id,rolename),表3:permission(id,permission),需要全部代码
好的,下面是一个简单的权限控制项目的代码,使用springboot+shiro+MyBatis,数据库表1:user(id,username,password),表2:role(id,rolename),表3:permission(id,permission)。
首先,需要在pom.xml中添加相关依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
接着,创建数据库表:
```sql
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rolename` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`permission` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `user_role` (
`user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`role_id`),
KEY `fk_user_role_role_id` (`role_id`),
CONSTRAINT `fk_user_role_role_id` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_user_role_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `role_permission` (
`role_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL,
PRIMARY KEY (`role_id`,`permission_id`),
KEY `fk_role_permission_permission_id` (`permission_id`),
CONSTRAINT `fk_role_permission_permission_id` FOREIGN KEY (`permission_id`) REFERENCES `permission` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_role_permission_role_id` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
然后,配置application.yml文件:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.shiro.entity
server:
port: 8080
```
接着,创建实体类:
User.java
```java
public class User implements Serializable {
private Integer id;
private String username;
private String password;
// getter、setter 略
}
```
Role.java
```java
public class Role implements Serializable {
private Integer id;
private String rolename;
// getter、setter 略
}
```
Permission.java
```java
public class Permission implements Serializable {
private Integer id;
private String permission;
// getter、setter 略
}
```
创建Mapper接口:
UserMapper.java
```java
@Mapper
public interface UserMapper {
User findByUsername(String username);
Set<String> findRolesByUsername(String username);
Set<String> findPermissionsByUsername(String username);
}
```
RoleMapper.java
```java
@Mapper
public interface RoleMapper {
Set<String> findRolesById(Integer id);
}
```
PermissionMapper.java
```java
@Mapper
public interface PermissionMapper {
Set<String> findPermissionsById(Integer id);
}
```
创建Mapper.xml文件:
UserMapper.xml
```xml
<mapper namespace="com.example.shiro.mapper.UserMapper">
<select id="findByUsername" parameterType="string" resultType="com.example.shiro.entity.User">
select * from user where username = #{username}
</select>
<select id="findRolesByUsername" parameterType="string" resultType="string">
select r.rolename from user u
join user_role ur on u.id = ur.user_id
join role r on ur.role_id = r.id
where u.username = #{username}
</select>
<select id="findPermissionsByUsername" parameterType="string" resultType="string">
select p.permission from user u
join user_role ur on u.id = ur.user_id
join role r on ur.role_id = r.id
join role_permission rp on r.id = rp.role_id
join permission p on rp.permission_id = p.id
where u.username = #{username}
</select>
</mapper>
```
RoleMapper.xml
```xml
<mapper namespace="com.example.shiro.mapper.RoleMapper">
<select id="findRolesById" parameterType="integer" resultType="string">
select rolename from role where id in (
select role_id from user_role where user_id = #{id}
)
</select>
</mapper>
```
PermissionMapper.xml
```xml
<mapper namespace="com.example.shiro.mapper.PermissionMapper">
<select id="findPermissionsById" parameterType="integer" resultType="string">
select permission from permission where id in (
select permission_id from role_permission where role_id in (
select role_id from user_role where user_id = #{id}
)
)
</select>
</mapper>
```
创建Realm类:
UserRealm.java
```java
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private PermissionMapper permissionMapper;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
String username = (String) principals.getPrimaryPrincipal();
Set<String> roles = userMapper.findRolesByUsername(username);
Set<String> permissions = userMapper.findPermissionsByUsername(username);
authorizationInfo.setRoles(roles);
authorizationInfo.setStringPermissions(permissions);
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
User user = userMapper.findByUsername(username);
if (user == null) {
throw new UnknownAccountException();
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
return authenticationInfo;
}
}
```
创建Controller类:
UserController.java
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(String username, String password) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
return "登录成功";
} catch (AuthenticationException e) {
return "登录失败";
}
}
@GetMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "退出成功";
}
@GetMapping("/test")
public String test() {
return "测试成功";
}
@GetMapping("/admin")
public String admin() {
return "admin权限访问成功";
}
@GetMapping("/user")
public String user() {
return "user权限访问成功";
}
}
```
创建Service类:
UserServiceImpl.java
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findByUsername(String username) {
return userMapper.findByUsername(username);
}
}
```
最后,创建启动类:
ShiroApplication.java
```java
@SpringBootApplication
@MapperScan("com.example.shiro.mapper")
public class ShiroApplication {
public static void main(String[] args) {
SpringApplication.run(ShiroApplication.class, args);
}
}
```
至此,简单的权限控制项目的代码就完成了。
阅读全文