MyBatis入门2
一、实现单一查询
1)核心配置文件:Configuration.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
3 <configuration>
4 <environments default="development">
5 <environment id="development">
6 <transactionManager type="JDBC" />
7 <!-- 配置数据库连接信息 -->
8 <dataSource type="POOLED">
9 <property name="driver" value="com.mysql.jdbc.Driver" />
10 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
11 <property name="username" value="root" />
12 <property name="password" value="XDP" />
13 </dataSource>
14 </environment>
15 </environments>
16
17 </configuration>
2)定义表所对应的实体类
package me.gacl.domain; /**
* @author gacl
* users表所对应的实体类
*/
public class User { //实体类的属性和表的字段名称一一对应
private int id;
private String name;
private int age; 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 int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
3)定义操作users表的sql映射文件userMapper.xml
<?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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
-->
<mapper namespace="me.gacl.mapping.userMapper">
<!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回
User类就是users表所对应的实体类
-->
<!--
根据id查询得到一个user对象
-->
<select id="getUser" parameterType="int"
resultType="me.gacl.domain.User">
select * from users where id=#{id}
</select>
</mapper>
4)在conf.xml文件中注册userMapper.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" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="XDP" />
</dataSource>
</environment>
</environments> <mappers>
<!-- 注册userMapper.xml文件,
userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
<mapper resource="me/gacl/mapping/userMapper.xml"/>
</mappers> </configuration>
5)编写测试代码:执行定义的select语句
package me.gacl.test; import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import me.gacl.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Test1 { public static void main(String[] args) throws IOException {
//mybatis的配置文件
String resource = "conf.xml";
//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
//Reader reader = Resources.getResourceAsReader(resource);
//构建sqlSession的工厂
//SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
/**
* 映射sql的标识字符串,
* me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
* getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
*/
String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串
//执行查询返回一个唯一user对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}
二、使用MyBatis对表执行CRUD操作——基于XML的实现
使用到的工具类:
package com.ual.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.Reader; public class MybatisUtil {
/**
* 获取sessionFactory
* @return SqlSessionFactory
*/
public static SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource="Configuration.xml";
Reader resourceAsReader = Resources.getResourceAsReader(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsReader);
return factory;
}
/**
* 获取sqlSession
* @return SqlSession
*/
public static SqlSession getSqlSession() throws IOException {
return getSqlSessionFactory().openSession();
}
/**
* 获取SqlSession
* @param isAutoCommit
* true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
* false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
* @return SqlSession
*/
public static SqlSession getSqlSession(boolean isAutoCommit) throws IOException {
return getSqlSessionFactory().openSession(isAutoCommit);
} }
1.UserMapper.xml映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2009-2016 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="User">
<resultMap type="com.ual.domain.User" id="UserResult">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
</resultMap>
<!--根据id查询一个User对象-->
<select id="getById" parameterType="Integer" resultMap="UserResult">
select * from user where id=#{id}
</select>
<!--创建用户-->
<insert id="addUser" parameterType="com.ual.domain.User">
insert into user(username,password)values (#{username},#{password})
</insert>
<!--删除用户-->
<delete id="deleteUser" parameterType="String">
delete from user where username=#{username}
</delete>
<!--查询全部用户-->
<select id="selectAll" resultMap="UserResult">
select * from user
</select>
</mapper>
2.dao实现类
package com.ual.dao; import com.ual.Utils.MybatisUtil;
import com.ual.domain.User;
import org.apache.ibatis.session.SqlSession; import java.util.List; public class UserDaoImpl implements UserDao {
SqlSession sqlSession=null;
@Override
public void selectById(Integer id) {
try{
sqlSession = MybatisUtil.getSqlSession();
User user = sqlSession.selectOne("User.getById",id);
System.out.println(user);
}catch (Exception e){
e.printStackTrace();
}finally {
if(sqlSession!=null)
sqlSession.close();
}
} @Override
public void insert(User user) {
try{
sqlSession = MybatisUtil.getSqlSession(true);
sqlSession.insert("User.addUser",user);
}catch (Exception e){
e.printStackTrace();
}finally {
if(sqlSession!=null)
sqlSession.close();
}
} @Override
public void deleteByName(String name) {
try{
sqlSession = MybatisUtil.getSqlSession(true);
sqlSession.insert("User.deleteUser",name);
}catch (Exception e){
e.printStackTrace();
}finally {
if(sqlSession!=null)
sqlSession.close();
}
} @Override
public void update(User user) { } @Override
public List<User> selectAll() {
try{
sqlSession = MybatisUtil.getSqlSession(true);
//查询到的结果,自动封装成List<User>
return sqlSession.selectList("User.selectAll");
}catch (Exception e){
e.printStackTrace();
}finally {
if(sqlSession!=null)
sqlSession.close();
}
return null;
}
}
3.单元测试
package com.ual; import com.ual.dao.MessageDao;
import com.ual.dao.UserDaoImpl;
import com.ual.domain.User; import java.util.List; public class Test {
@org.junit.Test
public void test(){
UserDaoImpl userDao = new UserDaoImpl();
userDao.selectById(1);
}
@org.junit.Test
public void test2(){
User user1 = new User();
user1.setUsername("xx");
user1.setPassword("1234");
UserDaoImpl userDao = new UserDaoImpl();
userDao.insert(user1);
}
@org.junit.Test
public void test3(){
UserDaoImpl userDao = new UserDaoImpl();
userDao.deleteByName("xx");
}
@org.junit.Test
public void test4(){
UserDaoImpl userDao = new UserDaoImpl();
List<User> users = userDao.selectAll();
for (User u:users
) {
System.out.println(u);
}
} }
三、使用MyBatis对表执行CRUD操作——基于注解的实现
1.定义sql映射的接口
package com.ual.Mapping; import com.ual.domain.User;
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 java.util.List; /**
* 定义映射的接口*/
public interface UserMapping {
//使用@Insert注解指明方法要执行的SQL
@Insert("insert into user(username,password )values(#{username},#{password})")
public int add(User user);
//使用@Deslete注解指明deleteByName方法要执行的sql
@Delete("delete from user where username=#{username}")
public int deleteByName(String name);
@Update("update user set username=#{username},password=#{password} where id= #{id}")
public int update(User user);
@Select("select * from user where id =#{id}")
public User getById(int id );
@Select("select * from user")
public List<User> getAll(); }
2、在conf.xml文件中注册这个映射接口
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2009-2016 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration>
<settings>
<setting name="useGeneratedKeys" value="false"/>
<setting name="useColumnLabel" value="true"/>
</settings> <typeAliases>
<typeAlias alias="User" type="com.ual.domain.User"/>
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="User.xml"/>
<!--注册UserMapping映射接口-->
<mapper class="com.ual.Mapping.UserMapping"/>
</mappers> </configuration>
3.测试
@org.junit.Test
public void test5() throws IOException {
SqlSession sqlSession = MybatisUtil.getSqlSession(true);
//获得会话后,获取接口,通过获取的接口调用里面定义的方法
UserMapping mapper = sqlSession.getMapper(UserMapping.class);
User user = new User();
user.setUsername("wzh");
user.setPassword("123o");
mapper.add(user);
sqlSession.close();
}
MyBatis入门2的更多相关文章
- MyBatis1:MyBatis入门
MyBatis是什么 MyBatis是什么,MyBatis的jar包中有它的官方文档,文档是这么描述MyBatis的: MyBatis is a first class persistence fra ...
- mybatis入门基础(二)----原始dao的开发和mapper代理开发
承接上一篇 mybatis入门基础(一) 看过上一篇的朋友,肯定可以看出,里面的MybatisService中存在大量的重复代码,看起来不是很清楚,但第一次那样写,是为了解mybatis的执行步骤,先 ...
- MyBatis入门基础(一)
一:对原生态JDBC问题的总结 新项目要使用mybatis作为持久层框架,由于本人之前一直使用的Hibernate,对mybatis的用法实在欠缺,最近几天计划把mybatis学习一哈,特将学习笔记记 ...
- MyBatis入门案例、增删改查
一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...
- mybatis入门_mybatis基本原理以及入门程序
一.传统jdbc存在的问题 1.创建数据库的连接存在大量的硬编码, 2.执行statement时存在硬编码. 3.频繁的开启和关闭数据库连接,会严重影响数据库的性能,浪费数据库的资源. 4.存在大量的 ...
- MyBatis入门学习教程-使用MyBatis对表执行CRUD操作
上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...
- MyBatis入门学习(二)
在MyBatis入门学习(一)中我们完成了对MyBatis简要的介绍以及简单的入门小项目测试,主要完成对一个用户信息的查询.这一节我们主要来简要的介绍MyBatis框架的增删改查操作,加深对该框架的了 ...
- MyBatis入门学习(一)
一.MyBatis入门简要介绍(百科) MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyB ...
- MyBatis入门案例 增删改查
一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...
- MyBatis入门(五)---延时加载、缓存
一.创建数据库 1.1.建立数据库 /* SQLyog Enterprise v12.09 (64 bit) MySQL - 5.7.9-log : Database - mybatis ****** ...
随机推荐
- CSS问题
当标签之间有缝隙 两个a标签之间消除缝隙 可在div设置 font-size:0 ul下的li去掉小圆点:设置 ul list-style:none <div> <a> & ...
- [references] How to Do Research
目录: ** 0x01 做研究/写论文的Alpha/Beta ** 0x02 How to Do Research | 经典指南 ** 0x03 思考写作与研究的区别 | The difference ...
- JQ高级
一.选择器 css语法选择器 $('css3 选择器位‘) 索引匹配 $('div:eq(0)') $('div').eq(0) 内容 $('div:contains(标签文本内容)') // 注:采 ...
- Codeforces Round #522 (Div. 2, based on Technocup 2019 Elimination Round 3) D. Barcelonian Distance 几何代数(简单)
题意:给出一条直线 ax +by+c=0 给出两个整点 (x1,y1) (x2,y2) 只有在x,y坐标至少有一个整点的时 以及 给出的直线才有路径(也就是格子坐标图的线上) 问 两个整点所需要 ...
- 命令行中的python一行流
优点是比那些古怪的脚本要易读 python -c 'import os, sys; [os.rename(a, a[0].upper()+a[1:]) for a in sys.argv[1:]]' ...
- Jupyter Notebook不能在系统命令行里全局启动
Anaconda安装好Juypyter Notebook之后,只能在base环境里启动,在系统的命令行里要全局启动Jupyter NoteBook失败了 C:\Users\HP>jupyter ...
- [BJOI2019]奥术神杖
https://www.luogu.org/problemnew/show/P5319 题解 首先观察我们要求的答案的形式: \[ \biggl(\prod V_i \biggr)^x\ \ \ x= ...
- python@wraps实现原理
@wraps作用 python中的装饰器装饰过的函数其实就不是函数本身了,我们可以看看下面的例子 import time def timmer(func): """tim ...
- virtualbox+ubuntu
https://jingyan.baidu.com/article/7f766daff541cd4101e1d0cd.html ubuntu 安装 这台计算机似乎没有安装操作系统 待解决 注意ubun ...
- laravel安装nova 运行php artisan migrate出错
报错一$ php artisan migrate Illuminate\Database\QueryException : could not find driver (SQL: select * f ...