月度归档:2021年03月

Springboot集成Mybatis

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

Mybatis架构

 

 

1. 添加maven 依赖

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>

2.添加相关配置文件(数据库链接等相关配置)

 

一、无配置文件注解版

1.在启动类中添加对mapper包扫描@MapperScan(或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种)

 

 2.开发Mapper

#{} 只是替换,相当于PreparedStatement使用占位符去替换参数,可以防止sql注入。 ${} 是进行字符串拼接,相当于sql语句中的Statement,使用字符串去拼接sql;$可以是sql中的任一部分传入到Statement中,不能防止sql注入。(比如说我们的入参是表名的时候,使用${})

    @Select 是查询类的注解,所有的查询均使用这个
    @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。

    @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
    @Update 负责修改,也可以直接传入对象@delete 负责删除

 

package com.qyc.Microservice.mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.qyc.Microservice.dto.User;

public interface UserMapper {

	@Insert("insert into user(age,name,password,sex) values (#{age},#{name},#{password},#{sex})")
	public void insert(User user);
	
	@Update("update user set name=#{name},age=#{age},password=#{password},sex=#{sex} where id=#{id}")
	public int update(User user);
	
	@Delete("delete from user where id=#{id}")
	public int delete(User user);
	
	@Select("select * from user where name = #{name} and password =#{password}")
	public User select(User user);
}

  

	@Test
	public void userSave() {
		User user = new User();
		user.setName("aa11a");
		user.setAge(20);
		user.setSex(0);
		user.setPassword("alsdja");
		
		userService.saveMapper(user);
	}

  

二、配置文件版

1 . pom文件和上个版本一样,只是application.properties新增以下配置
mybatis.config-locations=classpath:mybatis/mybatis-config.xml(可选)
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

 

linux中查看java进程

查看进程可以使用 

ps -ef|grep java

  

 

 

关闭某个进程 

比如:60355

 

 

  kill -9 60355

通过 ps -ef | grep java  得到如上线程将某线程终止时用 

kill -9 XXXXX     XXXXX为上述查出的序号  如: 19979线程终止为: kill -9 4834 

 

kill一个线程时需注意不要误停止了不应该停止的线程造成不必要的麻烦。 

在相当确信时才可用此方法停止线程。

mybatis关于jdbc连接报错,5.5.62MySQL连接,出现com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure等问题解决方法

首先mysql连接的驱动在5.7版本及之前驱动是

com.mysql.jdbc.Driver

在8.0更新之后需要注意,已经换成了以下的需要加cj

om.mysql.cj.jdbc.Driver

如果出现com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure等问题首先检查jdbc的url是否正确,在8.0以上需要注意,有些参数已经被废弃但是必须的参数有以下

jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncodeing=UTF-8&useSSL=false&serverTimezone=GMT

连接的符号也从“&”换成”&amp;“注意其他的符号在在xml文件中并不支持,有些参数已经被废弃,以上的都是在MySQL8.0版本出现的问题。

 

同时还需要检查驱动是否对应了版本号

参照地址:

https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-versions.html