最近搜索

创建一个简单的 mybatis-plush程序 增删除改查,和格式化时间

浏览:485
管理员 2022-04-06 16:01

最基础的增删除 改查。和格式化时间,2种格式,yyyy-MM-dd HH:mm:ss   yyyy-MM-dd

定义表名,定义字段名。

创建 springboot程序


大于小于查询,

某个字段等于 查询

某个like查询



贴上如下依赖


		<!-- 连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>
		<!-- 连接池 -->

		    <!-- 	JSONObject -->
		<dependency>    
		    <groupId>net.sf.json-lib</groupId>    
		    <artifactId>json-lib</artifactId>    
		    <version>2.4</version>    
		    <classifier>jdk15</classifier>    
		</dependency>  
		<!-- 	JSONObject -->
		


		<!--mybatis-plus插件3.4.3 -->
		<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.3</version>
		</dependency>
		<!--mybatis-plus插件3.4.3 -->
		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>



配置文件


server.port=80
server.servlet.context-path=/

#tomcat  jdbc
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/db_mybatis_plush?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#tomcat  jdbc

spring.servlet.multipart.maxFileSize=20MB
spring.servlet.multipart.maxRequestSize=20MB

 
#thymeleaf config
spring.thymeleaf.cache=false
#thymeleafconfig



创建user实体

@TableName("t_user")
public class User {
	@TableId(type=IdType.AUTO)//自动id
	private Integer id ;
	@TableField("name")//指定字段名
	private String name; 
	private String pwd  ; 
	private String trueName  ;
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")//不加timezone = "GMT+8"时间 好像不对。小时和分不对。
	private Date createDateTime  ;
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
	private Date tempDate  ;
	
	
	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 String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getTrueName() {
		return trueName;
	}
	public void setTrueName(String trueName) {
		this.trueName = trueName;
	} 	


还可以配置表前缀 我喜欢直接配置在实体上面

image.png




创建 mapper接口

/**
* @author 作者 豪哥
* @author 微信 xiaomao0055
* @author qq 14496453
* @version 日期 :2022年4月6日 下午11:24:19
*/
public interface UserMapper extends BaseMapper<User> {

}


service


public interface UserService {
	
	public void add(User user);
	public void update(User user) ;
	public  User findId(Integer id);
	public List<User> findAll();
	/**
	 * current默认1
	 */
	public List<User> list(Map<String,Object> map,Integer current,Integer pageSize);
	public void delete(Integer id );
	
	
}


实现类

@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Resource
	private	UserMapper userMapper;
	
	public void add(User user) {
		userMapper.insert(user);
	}
	
	public void update(User user) {
		userMapper.updateById(user);
	}
	
	public  User findId(Integer id){
		return userMapper.selectById(id);
	}
	
	public List<User> findAll(){
		//查询所有
		return userMapper.selectList(new LambdaQueryWrapper<>());
	}
	
	/**
	 * current默认1
	 */
	public List<User> list(Map<String,Object> map,Integer current,Integer pageSize){
		Page<User> page = new Page<User>(current,pageSize);
		
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>() ;
		queryWrapper.gt(User::getId, 5);//id大于5  可以自己写条件
		
		//参数1分页 参数2分页条件。
		Page<User> userPage =  userMapper.selectPage(page, queryWrapper);
		//总记录total
		System.out.println("总记录+"+userPage.getTotal());
		System.out.println("总页数"+userPage.getPages());
		return userPage.getRecords();
	}
	public void delete(Integer id ) {
		userMapper.deleteById(id) ;
	}

 
	
}





config配置文件


package com.java.cinfig;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

/**
 * 分页插件
 */
@Configuration
@MapperScan("com.java.mapper") // 扫描这个包。 @MapperScan("com.albb.server.**.mapper")
public class MyBatisPlushConfig {
	
	
	 // MybatisPlus在执行分页操作时,会被该拦截器拦截
    // 拦截器的作用 动态拼接where条件!!!
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MARIADB));
        return mybatisPlusInterceptor;
    }
    
	 
}


创建数据库,表。

image.png




写后台控制器


/**
* @author 作者 豪哥
* @author 微信 xiaomao0055
* @author qq 14496453
* @version 日期 :2022年5月1日 下午4:13:46
*/
@Controller
@RequestMapping("/admin/user")
public class Admin_User_Controller {
	
	@Resource
	private UserService  userService   ;
	
	/**
	 *  /admin/user/update
	 */
	@ResponseBody
	@RequestMapping("/add")
	public JSONObject add(User user) throws Exception {
		JSONObject result = new JSONObject();
		user.setCreateDateTime(new Date());
		user.setTempDate(new Date());
		userService.add(user);
		result.put("success", true );
		result.put("msg", "添加成功");
		return result;
	}
	
	/**
	 * /admin/user/update
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JSONObject update( User user)throws Exception {
		JSONObject result = new JSONObject();
		userService.update(user);
		result.put("success", true);
		result.put("msg", "修改成功");
		return result;
	}
	
	/**
	 * /admin/user/list
	 * @param page    默认1
	 * @param limit   数据多少
	 */
	@ResponseBody
	@RequestMapping("/list")
	public Map<String, Object> list(@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "limit", required = false) Integer limit, 
			HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<User> list = userService.list(map, page, limit);
		map.put("data", list);
		map.put("count", list.size());
		map.put("code", 0);
		map.put("msg", "");
		return map;
	}
	
	/**
	 * /admin/user/delete
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JSONObject delete(@RequestParam(value = "ids", required = false) String ids, HttpServletResponse response)
			throws Exception {
		String[] idsStr = ids.split(",");
		JSONObject result = new JSONObject();
		
		for (int i = 0; i < idsStr.length; i++) {
			try {
				userService.delete(Integer.parseInt(idsStr[i]));
			} catch (Exception e) {
				e.printStackTrace();
				result.put("success", false);
				return result;
			}
		}
		result.put("success", true);
		return result;
	}
	
}




写前端控制器

/**
* @author 作者 豪哥
* @author 微信 xiaomao0055
* @author qq 14496453
* @version 日期 :2022年5月1日 下午4:14:01
*/
@Controller
@RequestMapping("/houtai/user")
public class HouTai_User_Controller {
	@Resource
	private UserServiceImpl userService  ;
	/**
	 * /houtai/user/manage
	 */
	@RequestMapping("/manage")
	public ModelAndView manage() throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("title", "用户管理");
		mav.setViewName("/admin/page/user/user_manage");
		return mav;
	}
	/**
	 * /houtai/user/add
	 */
	@RequestMapping("/add")
	public ModelAndView add() throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("btn_text", "添加");
		mav.addObject("save_url", "/admin/user/add");
		mav.setViewName("/admin/page/user/add_update");
		return mav;
	}
	
	/**
	 * /houtai/user/edit?id=1
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(@RequestParam(value = "id", required = false) Integer id) throws Exception {
		ModelAndView mav = new ModelAndView();
		User user   = userService.findId(id);
		mav.addObject("user", user);
		mav.addObject("btn_text", "修改");
		mav.addObject("save_url", "/admin/user/update?id=" + id);
		mav.setViewName("/admin/page/user/add_update");
		return mav;
	}
	 
	
}



页面就是我们之前的页面省略








配置mapper。xml的文件位置


image.png






复杂的sql如何写

和之前ssm一样。配置文件也一样。




复杂的sql使用queryWrapper 大于如何写。


image.png



等于的查询,这是用的数据库表字段名,而不是实体的属性。必须保持一致最好。


System.out.println(name);  System.out.println(password);
Page<Staff> page = new Page<Staff>(1,10);
QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("staff_no",name);//工号帐号
Page<Staff> staffPage =  staffMapper.selectPage(page, queryWrapper);
System.out.println(staffPage.getPages());


模糊查询


    //查询数据
    @Override
    public OperateResult find(Staff object) {
        OperateResult operateResult = new OperateResult();
        //构造查询条件
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(object.getStaffNo()))
        {
            queryWrapper.like("staff_no",object.getStaffNo());
        }
        if(!StringUtils.isEmpty(object.getStaffName()))
        {
            queryWrapper.like("staff_name",object.getStaffName());
        }
        Page<Staff> page = new Page<>(object.getCurrentPage(), object.getPageSize());
        Page<Staff> data = this.page(page, queryWrapper);

        operateResult.setData(data);
        operateResult.setTotal(data.getTotal());
//        operateResult.setData(list(queryWrapper));
        return operateResult;
    }





文档核心写法。

https://baomidou.com/pages/10c804/#likeright


image.png








格式化时间 

image.png

	private String trueName  ;
	@JsonFormat(pattern = "yyyy-MM-dd")
	private Date date1  ;
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date date2  ;	

image.png

image.png

image.png




获取insert之后 获取id

插入之后id会回填到对象上面


image.png



如果不写这个注解,如果你把adress设置了内容,那么插入对象的时候会报错。

如果不写注解,也不设置address内容,那么插入对象不报错。

不关联数据库表字段。


image.png







联系站长

站长微信:xiaomao0055

站长QQ:14496453