我是靠谱客的博主 斯文项链,最近开发中收集的这篇文章主要介绍第一个Mybatis程序,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1、第一个Mybatis程序

思路:搭建环境–>导入Mybatis–>编写代码–>测试!
1.1、搭建环境

搭建数据库

CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'java','123456'),
(2,'c++','123456'),
(3,'c','123890')

新建项目

新建一个普通的maven项目
删除src目录
导入maven依赖

<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>

2.2、创建一个模块

编写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核心配置文件-->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>

编写mybatis工具类


//sqlSessionFactory --> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
// SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
public static SqlSession
getSqlSession(){
return sqlSessionFactory.openSession();
}
}

2.3、编写代码
实体类


package com.kuang.pojo;
//实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = 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 + ''' +
'}';
}
}

Dao接口


public interface UserMapper {
//获取全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//插入用户
int addUser(User user);
//修改用户
int updateUser(User user);
//删除用户
int deleteUser(int id);
int addUser1(Map<String,Object> map);
List<User>
getUserLike(String value);
}
接口实现类由原来的UserDaoImpl转变为一个 Mapper配置文件.

<?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.kuang.dao.UserMapper">
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user1
</select>
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
select * from mybatis.user1 where id=#{id}
</select>
<select id="getUserById2" parameterType="map" resultType="com.kuang.pojo.User">
select * from mybatis.user1 where id=#{id} and name=#{name};
</select>
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into mybatis.user1 (id,name,pwd)value (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.kuang.pojo.User">
update mybatis.user1 set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<delete id="deleteUser" parameterType="com.kuang.pojo.User">
delete
from mybatis.user1
where id=#{id};
</delete>
<insert id="addUser1" parameterType="map">
insert into mybatis.user1 (id,name,pwd) value (#{userid},#{userName},#{password});
</insert>
<select id="getUserLike" resultType="com.kuang.pojo.User">
select * from mybatis.user1
where name like "%"#{value}"%"
</select>
</mapper>

2.4、测试

注意点:

org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?

核心配置文件中注册 mappers

junit测试

public class UserDaoTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
//方式一
//
UserDao mapper = sqlSession.getMapper(UserDao.class);
//
List<User> userList = mapper.getUserList();
//方式二
List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
//sqlSession.close();
}
@Test
public void getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(3, "一年", "123489"));
if (res > 0) {
System.out.println("插入成功!~~~");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser()
{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(2,"守望","157489"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser()
{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(1);
sqlSession.commit();
sqlSession.close();
}
public void addUser2()
{
SqlSession sqlSession=MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> Map = new HashMap<>();
Map.put("user",5);
Map.put("password","23333");
mapper.addUser1(Map);
}
@Test
public void getUserById2()
{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("helloid",1);
mapper.addUser1(map);
sqlSession.close();
}
@Test
public void getUserLike()
{
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("%守%");
for (User user :
userLike) {
System.out.println(user);
}
sqlSession.commit();
sqlSession.close();
}
}

可能会遇到的问题:

配置文件没有注册
绑定接口错误。
方法名不对
返回类型不对
Maven导出资源问题

最后

以上就是斯文项链为你收集整理的第一个Mybatis程序的全部内容,希望文章能够帮你解决第一个Mybatis程序所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部