1. 引包

  • 本例中使用maven构造项目,所以只需配置依赖即可引相应的包。

pom.xml

<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>com.shyrolk</groupId>
<artifactId>firstMybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>firstMybatis</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency> <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies> </project>

2. 编写mybatis总配置文件mybatis-config.xml和log4j.properties

<?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/test?useUnicode=true&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments> </configuration>

log4j.properties:

    # Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  • 开发环境中建议rootLogger=DEBUG

1.3  创建数据库和实体

  1.3.1 创建数据库

  1.3.2 创建实体对象

package com.shyroke.entity;

public class User {
private int id;
private String userName;
private String passWord; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassWord() {
return passWord;
} public void setPassWord(String passWord) {
this.passWord = passWord;
} @Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord + "]";
} }

1.5 编写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="test"> <!-- 根据 id 查询 user 表中的数据
id:唯一标识符,此文件中的id值不能重复
resultType:返回值类型,一条数据库记录也就对应实体类的一个对象
parameterType:参数类型,也就是查询条件的类型
-->
<select id="findUserById"
resultType="com.shyroke.entity.User" parameterType="int">
<!-- 这里和普通的sql 查询语句差不多,后面的 #{id}表示占位符,里面不一定要写id,写啥都可以,但是不要空着 -->
select * from user where id = #{id}
</select> <!-- 模糊查询 -->
<select id="findUserByName" resultType="com.shyroke.entity.User" parameterType="java.lang.String">
select * from user where userName like '%${_parameter}%'
</select> </mapper>
  •   1. 如果仅传入一个类型为String的参数,那么在 xml文件中应该使用_parameter来代替参数名。
  • 2. '%${_parameter}%' 这里只能用${} 而不能用#{},如果用#{},因为#{}相当于占位符?,
    sql语句就为like '%${?}%' 中占位符?被单引号所包围,此时?会被作为参数传入,而不会传真正的参数传入。
  •  3. #{} 和${}区别:
    当使用#时变量是占位符,就是一般我们使用java jdbc的PrepareStatement时的占位符?,所有可以防止sql注入
    当使用$时,变量就是直接追加在sql中,一般会有sql注入问题。

1.6 加载UserMapper.xml文件

  • 在mybatis的总配置文件mybatis-config.xml中添加
    <mappers>
  <mapper resource="com/shyroke/mapper/UserMapper.xml"/>
</mappers>

1.7 测试

package com.shyrolk.firstMybatis;

import java.awt.image.ImageProducer;
import java.io.InputStream;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.shyroke.entity.User; /**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{ InputStream inputStream=App.class.getClassLoader().getResourceAsStream("resource/mybatis-config.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession(); User user=sqlSession.selectOne("test.findUserById", 1);
List<User> userList=sqlSession.selectList("test.findUserByName", "a");
System.out.println(userList);
sqlSession.close();
}
}

结果:

(二)第一个mybatis项目的更多相关文章

  1. 第一个Mybatis项目

    第一个Mybatis项目 一.创建普通Maven项目 1.配置pom.xml文件 <dependencies> <!--mysql驱动--> <dependency> ...

  2. MyBatis学习笔记(一)创建第一个MyBatis项目

    一.新建Maven项目 http://www.mybatis.org/mybatis-3/zh/index.html 该链接为MyBatis官方地址 创建MyBatis项目主要有两种办法,一种是导入j ...

  3. 我的第一个Mybatis项目搭建

    1.新建maven项目,目录如下.第一个坑idea目录和eclipse不一样project就像workspace pom文件 jdk版本有点高建议8.0 <?xml version=" ...

  4. IDEA构建一个mybatis项目

    目录结构如下: 在pom.xml中配置需要的jar包 <dependencies> <dependency> <groupId>org.mybatis</gr ...

  5. MyBatis项目快速搭建及MySQL一个Statement支持多条命令参数

    一.简述 本文以笔记的形式,记录一个基本Mybatis项目的使用,方便后期项目使用到相关配置时直接复制使用. 二.项目结构 pom.xml中的依赖 <!-- https://mvnreposit ...

  6. 带你搭建一个简单的mybatis项目:IDEA+spring+springMVC+mybatis+Mysql

    最近小编有点闲,突发奇想想重温一下mybatis,然后在脑海中搜索了一下,纳尼,居然不太会用了,想到这里都是泪啊!!现在我所呆的的公司使用的是springboot+hebinate,编程都是使用的JP ...

  7. mybatis入门教程之搭建一个简单的mybatis项目并启动它

    一.准备条件: 1.依赖jar包:mybatis核心包(必须).lombok插件包(非必须)以及MySQL数据库连接驱动包(必须) <dependency> <groupId> ...

  8. J2EE SSH学习(二)安装Eclipse插件和第一个Eclipse项目

    (一)安装Eclipse插件 Eclipse有很多功能很强大的插件,我现在作为一个菜鸟只知道插件的功能通常都很牛叉实用或者很有趣,那么该怎么安装Eclipse插件呢? 我使用的是Eclipse 4.3 ...

  9. SuperSocket基础(二)-----一个完成SocketServer项目

    SuperSocket基础(二)-----一个完成SocketServer项目 由于时间关系未能及时更新,关于SuperSocket,对于初学者而言,一个SuperSock的Server真的不好写.官 ...

随机推荐

  1. TXMLDocument 的使用

    TXMLDocument 的使用 TXMLDocument是DELPHI自带的操作XML的类. 需要它,需要引用单元: uses XMLDoc; var XMLDoc:TXMLDocument; XM ...

  2. Python网络爬虫学习手记(1)——爬虫基础

    1.爬虫基本概念 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.--------百度百科 简单的说,爬 ...

  3. telnet nmap netstap

    yum install nmap [root@10-13-109-236 ~]# nmap localhost Starting Nmap 6.40 ( http://nmap.org ) at 20 ...

  4. Python 中的 -> 是什么意思

    函数标注通常用于 类型提示:例如以下函数预期接受两个 int 参数并预期返回一个 int 值:```def sum_two_numbers(a: int, b: int) -> int:retu ...

  5. 【转载】 AutoML技术现状与未来展望

    原文地址: https://www.cnblogs.com/marsggbo/p/9309520.html ---------------------------------------------- ...

  6. js实现文本框支持加减运算的方法

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/T ...

  7. Javescript——API连接 && json数据处理(待续)

    原文链接1:How to Connect to an API with JavaScript 原文链接2:How to Use the JavaScript Fetch API to Get JSON ...

  8. 阶段5 3.微服务项目【学成在线】_day17 用户认证 Zuul_10-前端显示当前用户-jwt查询接口

    定义接口 在api的项目里面定义.AuthControllerApi里面定义接口 jwtResult,里面就有一个jwt的字段. 实现接口 需要这三步 定义私有方法从cookie中读取访问令牌 参数需 ...

  9. Python基础之set集合与函数

    set集合 集合是一个无序且不重复的元素组合,以大括号表示.使用详情: >>> b=set(a) >>> type(b) <class 'set'> & ...

  10. PAT 甲级 1042 Shuffling Machine (20 分)(简单题)

    1042 Shuffling Machine (20 分)   Shuffling is a procedure used to randomize a deck of playing cards. ...