连接数据库:
端口号:
打开IDEA:
注意这个URL:jdbc:mysql://localhost:3308
对应mybatis核心配置的url;
新建IDEA的MAVEN项目
目录:
数据库:
打开可视化管理工具:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>twoone</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-01</module>
</modules>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>
**/*.properties
</include>
<include>
**/*.xml
</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
核心配置:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--核心配置文件-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3308/data1?useSSL=true&userUnicode=true&
characterEncoding=UTF-8"/>
<property name="username" value="heziyi"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 每一个mapper.xml都需要在mybatis的核心配置文件中注册!!-->
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
</configuration>
select 标签中的 select * from data1.user where id = #{id}是查询语句。
{id} : MyBatis SQL 中使用预编译参数的一种方式,大括号中的id 是传入的参数名。
UserDao.java:
package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserlist();
User getUserById(int id);
}
Usemapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.UserDao">
<select id="getUserlist" resultType="com.kuang.pojo.User" >
select * from data1.user
</select>
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
select * from data1.user where id = #{id}
</select>
</mapper>
当Mapper 接口和XML 文件关联的时候**,命名空间namespace 的值就需要配置成接口的全限定名称,**例如UserMapper 接口对应的com.kuang.dao.UserDao, MyBatis 内部就是通过这个值将接口和XML 关联起来的。
resultType :定义了当前查询的返回值类型,此处就是指实体类Country ,前面配置中提到的别名主要用于这里,如果没有设置别名,此处就需要写成resultType=com.kuang.pojo.User
pojo.user:
package com.kuang.pojo;
public class User {
private int id;
private String name;
private String pwd;
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
utils下的MyBatistutils:
package com.kuang.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory --> sqlsession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory ;
static {
try {
String resource = "mybatis-config.xml";
//放在static中,这样初始时就会加载
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}//既然有了sqlSessionFactory 顾名思义,我们可以从中获得sqlSession的实例了
//SqlSession完全包含了面向数据执行SQL命令的所有方法
public static SqlSession getSqlSession(){
// SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSessionFactory.openSession();
}
}
测试类:
package com.kuang;
import com.kuang.dao.UserDao;
import com.kuang.pojo.User;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaotest {
@Test
public void test() {
//第一步:获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行SQL
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserlist();
for (User user : userList) {
System.out.println(user);}
sqlSession.close();//关闭
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao dao = sqlSession.getMapper(UserDao.class);//获得接口
User user = dao.getUserById(1);
System.out.println(user);
sqlSession.close();
}
}
测试test()结果:
查找id为1的数据:
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao dao = sqlSession.getMapper(UserDao.class);//获得接口
User user = dao.getUserById(1);
System.out.println(user);
sqlSession.close();
}
插入:
UserDao接口中增加一句:
int adduser(User user);
在xml中增加:
<insert id="adduser" parameterType="com.kuang.pojo.User" >
insert into data1.user(id,name ,pwd) values (#{id},#{name},#{pwd});
</insert>
测试类中增加:
@Test
public void adduser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao addd = sqlSession.getMapper(UserDao.class);
int count = addd.adduser(new User(3,"哈哈","14231"));
if(count > 0){
System.out.println("nice");
}
sqlSession.commit();//增删改需要提交事务
sqlSession.close();
}
查看刚刚的表已经增加了一个:
修改:
测试类:
@Test
public void updateu(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao updated = sqlSession.getMapper(UserDao.class);
updated.updateu(new User(3,"婧婧","14231"));
sqlSession.commit();//提交事务
sqlSession.close();
}
接口中增加:
void updateu(User user);//xml文件update中对应的id是方法名
xml中增加:
<update id="updateu" parameterType="com.kuang.pojo.User">
update data1.user set name=#{name},pwd = #{pwd} where id = #{id};
</update>
表发生了修改:
删除:
测试类:
@Test
public void deleteuser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao deleteuser = sqlSession.getMapper(UserDao.class);
deleteuser.deleteuser(1);
sqlSession.commit();//提交事务
sqlSession.close();
}
xml文件修改:
<delete id="deleteuser" parameterType="int">
delete from data1.user where id = #{id};
</delete>
UserDao接口:
int deleteuser(int id);
运行之后查看表发现已经删除了id为1的数据:
利用万能map插入数据:
resultMap 是一种很重要的配置结果映射的方法,
id :必填,并且唯一。在select 标签中, resultMap 指定的值即为此处id 所设置的值。resultMap 包含的所有属性如下。
• type :必填,用于配置查询列所映射到的Java 对象类型。
extends : 选填,可以配置当前的resultMap 继承自其他的re sultMap ,属性值为
继承resultMap 的id 。
autoMapping :选填,可选值为true 或false ,用于配置是否启用非映射字段(没有在resultMap 中配置的字段〉的自动映射功能, 该配置可以覆盖全局的
autoMappingBehavior 配置。
测试类:
@Test
public void adduser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao add1 = sqlSession.getMapper(UserDao.class);
HashMap<String,Object> map = new HashMap<String,Object>();
// userid},#{username},#{password
map.put("userid",5);
map.put("username","梁梁子");
map.put("password","12412");
add1.adduser2(map);
sqlSession.commit();//提交事务
sqlSession.close();
}
xml:
<insert id="adduser2" parameterType="map">
insert into data1.user(id,name,pwd) values (#{userid},#{username},#{password});
</insert>
UserDao.java:
//用map传对象
int adduser2(Map<String,Object> map);
运行测试类后查看user表
注意:
假设实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
模糊查询
测试类
@Test
public void getuserlike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao getuser2 = sqlSession.getMapper(UserDao.class);
List<User> userList = getuser2.getuserlike("%梁%");
for (User user:userList){
System.out.println(user);
}
sqlSession.close();
}
xml:
<select id="getuserlike" resultType="com.kuang.pojo.User">
select * from data1.user where name like #{value}
</select>
接口:
List<User> getuserlike(String name);
运行:
注意:要传递通配符,即%
故下面的代码应该注意:
List<User> userList = getuser2.getuserlike("%梁%");
也可以在Sql拼接中使用通配符 即改成在xml中写上:
<select id="getuserlike" resultType="com.kuang.pojo.User">
select * from data1.user where name like "%"#{value}"%"
</select>
上面这句话改为:
List<User> userList = getuser2.getuserlike("梁");
接口可以配合XML 使用,也可以配合注解来使用。XML 可以单独使用,但是注解必须在接口中使用。