环境搭建
1.pom.xml添加依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
2.新建数据表account
use mybatis;
create table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int
)
3.新建数据表对应的实体类Account
- 在
pom.xml
中引入lombok
可以简化实体类的编写。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
- 编写
Account
实体类的时候加注解即可
package com.southwind.entity;
import lombok.Data;
@Data
public class Account {
private long id;
private String username;
private String password;
private int age;
}
4.创建Mybatis配置文件config.xml
- 要先加
dtd
的配置文档
<?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>
<!-- 配置MyBatis运行环境 -->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED配置JDBC数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?
useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="daq"></property>
</dataSource>
</environment>
</environments>
</configuration>
Mybatis开发的两种方式
Mybatis
开发的两种方式,使用原生接口和使用Mapper
代理实现自定义接口。
(一)使用原生接口
Mybatis框架需要开发者自定义SQL语句,写在Mapper.xml
文件中,实际开发中会为每个实体类创建对应的Mapper.xml
,定义管理对象数据的SQL。
- 为
account
实体类创建AccountMapper.xml
,
如下: 先引入dtd
头文件。
namesapce
通常设置为文件所在包+文件名的形式。
insert
标签—>添加,select
—>查询,update
—>更新,delete
—>删除
id
使实际调用MyBatis
方法时需要用到的参数。
parameterType
是调用对应方法时参数的数据类型。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.southwind.mapper.AccoutMapper">
<insert id="save" parameterType="com.southwind.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>
</mapper>
- 在全局配置文件
config.xml
中注册AccountMapper.xml
<!-- 注册AccountMapper.xml -->
<mappers>
<mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
</mappers>
- 调用
Mybatis
原生接口来执行添加操作
public class Test {
public static void main(String[] args) {
//加载MyBatis配置文件
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.southwind.mapper.AccoutMapper.save";
Account account = new Account(1L,"张三","123123",22);
sqlSession.insert(statement,account);
sqlSession.commit();
sqlSession.close();
}
}
注:maven
工程不会读取java中的配置文件,他默认只会读取resource
中的,解决办法就是,在pom.xml
中添加配置
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
(二)使用Mapper代理实现自定义接口
只需要把方法定义好,相应的Sql
语句在Mapper.xml
中定义好,其他的就不用管了。只需要拿到对象就可以了。
- 自定义接口,定义好相关的业务方法。
public interface AccountRepository {
public int save(Account account);
public int update(Account account);
public int deleteById(long id);
public List<Account> findAll();
public Account findById(long id);
public Account findByName(String name);
public Account findById2(Long id);
public Account findByNameAndAge(String name,int age);
public int count();
public Integer count2();
public String findNameById(long id);
public Account findByAccount(Account account);
public List<Account> findByIds(Account account);
}
- 创建接口对应的
Mapper.xml
,定义接口方法对应的SQL语句。
statement
标签可根据SQL执行的业务选择insert,delete,update,select
Mybatis
框架会根据规则来自动创建接口实现类的代理对象
规则:
Mybatis.xml
中namespace
为接口的全类名。Mybatis.xml
中statement
的id为接口中对应的方法名。Mybatis.xml
中statement
的parmeterType
和接口中对应方法的参数类型一致。Mybatis.xml
中statement
的resultType
和接口中对应方法的返回值类型一致。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.southwind.repository.AccountRepository">
<insert id="save" parameterType="com.southwind.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>
<update id="update" parameterType="com.southwind.entity.Account">update t_account
set username = #{username},password = #{password},age= #{age} where id = #{id}
</update>
<delete id="deleteById" parameterType="long">
delete from t_account where id = #{id}
</delete>
<select id="findAll" resultType="com.southwind.entity.Account">
select * from t_account
</select>
<select id="findById" parameterType="long" resultType="com.southwind.entity.Account">
select * from t_account where id = #{id}
</select>
</mapper>
- 在
config.xml
中注册AccountRepository.xml
,追加一个mapper
标签即可。
<mappers>
<mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
<mapper resource="com/southwind/repository/AccountRepository.xml"></mapper>
</mappers>
- 测试增删改查
public class Test2 {
public static void main(String[] args) {
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取实现接口的代理对象,这就设计到动态代理,CGLib动态代理具体类,获取到代理对象
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
//添加对象
Account account = new Account(3L,"王五","111111",24);
int result = accountRepository.save(account);
sqlSession.commit();
//查询全部对象
List<Account> list = accountRepository.findAll();
for (Account account:list){
System.out.println(account);
}
sqlSession.close();
//通过id查询对象
Account account = accountRepository.findById(3L);
System.out.println(account);
sqlSession.close();
//修改对象
Account account = accountRepository.findById(3L);
account.setUsername("小明");
account.setPassword("000");
account.setAge(18);
int result = accountRepository.update(account);
sqlSession.commit();
System.out.println(result);
sqlSession.close();
//通过id删除对象
int result = accountRepository.deleteById(3L);
System.out.println(result);
sqlSession.commit();
System.out.println(accountRepository.findByName("张三"));
Long id = Long.parseLong("1");
System.out.println(accountRepository.findById2(id));
System.out.println(accountRepository.findByNameAndAge("张三",22));
System.out.println(accountRepository.count());
System.out.println(accountRepository.count2());
System.out.println(accountRepository.findNameById(1L));
sqlSession.close();
}
}
转载:https://blog.csdn.net/weixin_44861399/article/details/106113748
查看评论