MyBatis入门配置及增删改查
Posted 爽走不解释
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis入门配置及增删改查相关的知识,希望对你有一定的参考价值。
一、MyBatis简介
1、什么是MyBatis?
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。
2、MyBatis的优点
1. 与JDBC相比,减少了50%以上的代码量。
2. MyBatis是最简单的持久化框架,小巧并且简单易学。
3. MyBatis灵活,不会对应用程序或者数据库的现有设计强加任何影响,SQL写在XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,可重用。
4. 提供XML标签,支持编写动态SQL语句(XML中使用if, else)。
5. 提供映射标签,支持对象与数据库的ORM字段关系映射(在XML中配置映射关系,也可以使用注解)。
3、MyBatis框架的缺点
1. SQL语句的编写工作量较大,尤其是字段多、关联表多时,更是如此,对开发人员编写SQL语句的功底有一定要求。
2. SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库。
4、MyBatis框架适用场合:
MyBatis专注于SQL本身,是一个足够灵活的DAO层解决方案。
对性能的要求很高,或者需求变化较多的项目,如互联网项目,MyBatis将是不错的选择。
二、代码操作
整个项目的类图,记得导入相关的jar包
1、首先建好表 然后写成实体类
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) NOT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
INSERT INTO `users` VALUES ('1', '猪八戒', '2021-04-29', '男', '中国');
INSERT INTO `users` VALUES ('3', '猪猪侠', '2021-04-20', '女', '西国');
INSERT INTO `users` VALUES ('8', '沙悟净', null, '妖', null);
INSERT INTO `users` VALUES ('10', '沙悟净', null, '妖', null);
INSERT INTO `users` VALUES ('12', '沙悟净', '2001-08-03', '妖', '西北');
INSERT INTO `users` VALUES ('13', '李村', '2002-02-02', '男', '黄土坡');
SET FOREIGN_KEY_CHECKS=1;
2、配置adbc.properties
jdbc.url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
jdbc.username = root
jdbc.password = 123456
jdbc.driver = com.mysql.jdbc.Driver
3、新建MyBatis配置文件
<?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>
<!--引入jdbc的配置文件-->
<properties resource="jdbc.properties"/>
<settings>
<!-- 开启驼峰映射:数据库:user_name ===> java:userName -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="zxy.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--配置sql映射文件-->
<mappers>
<package name="zxy.mapper"/>
</mappers>
</configuration>
4、配置增删改查的mapper接口
5、配置数据映射
<?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">
<!--namespace:命名空间 用于唯一一个sql标识-->
<mapper namespace="zxy.mapper.UserMapper">
<!--sql映射 id:sql对应映射的唯一标识-->
<select id="selectUser" resultType="user" >
select * from users where username like '__戒'
</select>
<insert id="insertUser" parameterType="zxy.entity.User">
insert into users VALUE (#{id},#{username},#{birthday},#{sex},#{address})
</insert>
<insert id="insert" parameterType="zxy.entity.User"
useGeneratedKeys="true" keyProperty="id">
insert into users(username,birthday,sex,address) VALUE (#{username},#{birthday},#{sex},#{address})
</insert>
<update id="updateUser" parameterType="zxy.entity.User">
update users set username=#{username},#{birthday},sex=#{sex},#{address where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete>
<insert id="insertCopy" parameterType="users" >
<selectKey keyProperty="id" order="BEFORE" resultType="String">
select uuid();
</selectKey>
insert into users_copy(id,username,birthday,sex,address) VALUE (#{id},#{username},#{birthday},#{sex},#{address})
</insert>
<select id="findByid" resultType="user">
select
id,username,sex,birthday,address from ${tbName}
where
id=#{id}
and
username=#{userName}
</select>
</mapper>
6、测试写好的增删改查
public class text1 {
SqlSessionFactory sqlSessionFactory;
@Before
public void init() {
try {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void update(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
//mapper.updateUser(new User(88,"猪八戒","女","2000-8-22","东岸"));
session.commit();
session.close();
}
@Test
public void delect(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
mapper.deleteUser(2);
session.commit();
session.close();
}
@Test
public void insert(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
//mapper.insertUser(new User(12,"沙悟净","妖","2001-8-3","西北"));
session.commit();
session.close();
}
@Test
public void select(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User ss = mapper.selectUser("");
System.out.println(ss);
session.commit();
session.close();
}
@Test
public void inserts(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user =new User();
user.setUsername("李村");
user.setBirthday("2002-2-2");
user.setSex("男");
user.setAddress("黄土坡");
int rest= mapper.insert(user);
System.out.println("rest==="+rest);
System.out.println("getid==="+user.getId());
session.commit();
session.close();
}
@Test
public void insertCopy(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
Usre_Copy user =new Usre_Copy();
user.setUsername("老王");
user.setBirthday("2002-2-2");
user.setSex("女");
user.setAddress("黄土高坡");
int rest = mapper.insertCopy(user);
System.out.println("rest==="+rest);
System.out.println("getid==="+user.getId());
session.commit();
session.close();
}
@Test
public void findByid(){
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User byid = mapper.findByid(1, "猪八戒", "users");
System.out.println("user"+byid);
}
@Test
public void testorder(){
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
OrderMapper mapper = session.getMapper(OrderMapper.class);
Order orderUserByid = mapper.findOrderUserByid(100);
System.out.println("结果=="+orderUserByid);
}
}
以上是关于MyBatis入门配置及增删改查的主要内容,如果未能解决你的问题,请参考以下文章