最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊

第一個(gè)mybatis程序,實(shí)現(xiàn)增刪改查CRUD

2020-04-17 22:23 作者:xiezhr  | 我要投稿

mybatis 介紹

????????????? mybatis 本是apache的一個(gè)開源項(xiàng)目iBatis,
2010年這個(gè)項(xiàng)目由apache遷移到了googlecode,并且改名為MyBatis,2013年11月遷移到Github。

????????????? MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲(chǔ)過程以及高級(jí)映射。

????????????? MyBatis 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集。

????????????? MyBatis 可以使用簡單的 XML 或注解來配置和映射原生信息,將接口和 Java 的 POJOs(普通的 Java對象)映射成數(shù)據(jù)庫中的記錄

Mybatis官方文檔 :
http://www.mybatis.org/mybatis-3/zh/index.html

GitHub :https://github.com/mybatis/mybatis-3

代碼演示

1.????????? 所需環(huán)境

????????????? jdk1.8.0_91

????????????? mysql-5.7.29

????????????? apache-maven-3.6.3

1.????????? 創(chuàng)建數(shù)據(jù)庫

CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert? into `user`(`id`,`name`,`pwd`) values (1,'張三','123456'),(2,'李四','abcdef'),(3,'王五','987654');

1.????????? 使用idea創(chuàng)建項(xiàng)目并導(dǎo)入導(dǎo)入mybatis所需jar包

<dependencies>
??????? <!--mysql驅(qū)動(dòng)-->
??????? <dependency>
??????????? <groupId>mysql</groupId>
??????????? <artifactId>mysql-connector-java</artifactId>
??????????? <version>5.1.46</version>
??????? </dependency>
??????? <!--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>

1.????????? 編寫mybatis核心配置文件

==該配置文件主要是配置連接mysql的基本信息及注冊mapper(具體配置參考官方文檔)==

<?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?useUnicode=true&amp;characterEncoding=utf-8"/>
??????????????? <property name="username" value="root"/>
??????????????? <property name="password" value="123456"/>
??????????? </dataSource>
??????? </environment>
??? </environments>

??? <mappers>
??????? <mapper resource="com/xiezhr/Dao/UserMapper.xml"></mapper>
??? </mappers>
</configuration>

1.????????? 編寫mybatis工具類

==查看官方文檔,我們這里要封裝一個(gè)工具類生成SqlSession對象,SqlSession用于后面的執(zhí)行sql==

package com.xiezhr.util;

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.InputStream;

public class MysqlUtil {

??? private static SqlSessionFactory sqlSessionFactory;
??? static {
??????? String resource = "mybatis-config.xml";
??????? InputStream inputStream = null;
??????? try {
??????????? inputStream = Resources.getResourceAsStream(resource);
??????? } catch (IOException e) {
??????????? e.printStackTrace();
??????? }
???????? sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

??? }

??? public static SqlSession getSqlSession(){
??????? return sqlSessionFactory.openSession();
??? }


}

1.????????? 創(chuàng)建對應(yīng)數(shù)據(jù)庫表的實(shí)體類

==各個(gè)屬性得命名必須與數(shù)據(jù)庫字段一一對應(yīng),具體如下所示,數(shù)據(jù)庫對應(yīng)字段為id,name,pwd==

package com.xiezhr.pojo;

public class User {
??? private int id;
??? private String name;
??? private String pwd;

??? public String getPwd() {
??????? return pwd;
??? }

??? public void setPwd(String pwd) {
??????? this.pwd = pwd;
??? }

??? public String getName() {
??????? return name;
??? }

??? public void setName(String name) {
??????? this.name = name;
??? }

??? public int getId() {
??????? return id;
??? }

??? public void setId(int id) {
??????? this.id = id;
??? }

??? public User() {
??? }

??? public User(int id, String name, String pwd) {
??????? this.id = id;
??????? this.name = name;
??????? this.pwd = pwd;
??? }

??? @Override
??? public String toString() {
??????? return "User{" +
??????????????? "id=" + id +
??????????????? ", name='" + name + '\'' +
??????????????? ", pwd='" + pwd + '\'' +
??????????????? '}';
??? }
}

1.????????? 編寫Mapper接口

==該接口對應(yīng)原來的dao,具體代碼如下==

package com.xiezhr.dao;

import com.xiezhr.pojo.User;

import java.util.List;

public interface UserMapper {
??? List<User> getUserList();
}

1.????????? 編寫Mapper.xml 文件

==由于我們使用了mybatis,所以這的xml文件相當(dāng)于我們原來dao得實(shí)現(xiàn)類daoimpl。namespace屬性對應(yīng)著接口,不能寫錯(cuò),標(biāo)簽表示是個(gè)查詢語句。id 屬性對應(yīng)著接口的方法,result Type代表返回得類型,即對應(yīng)這pojo實(shí)體。具體代碼如下==

<?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.xiezhr.dao.UserMapper">
??? <select id="getUserList" resultType="com.xiezhr.pojo.User">
???? select * from mybatis.user;
??? </select>
</mapper>

1.????????? 到這一步我們第一個(gè)mybatis實(shí)現(xiàn)查詢就基本大功告成了,接下來就要編寫測試類測試我們寫得代碼

package com.xiezhr.dao;

import com.xiezhr.pojo.User;
import com.xiezhr.util.MysqlUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class TestUserDao {
??? @Test
??? public void selectUser(){
??????? SqlSession sqlSession = MysqlUtil.getSqlSession();
??????? UserMapper mapper = sqlSession.getMapper(UserMapper.class);
??????? List<User> userList = mapper.getUserList();

??????? for (User user : userList) {
??????????? System.out.println(user);
??????? }

??? }
}

經(jīng)過測試后輸出測試結(jié)果

User{id=1, name='張三', pwd='322334'}
User{id=2, name='李四', pwd='123456'}
User{id=3, name='王五', pwd='123456'}

==擴(kuò)展==

????????????? 根據(jù)id查詢用戶

????????????? 1.在UserMapper接口中添加相應(yīng)的方法selectUserById(id)

public interface UserMapper {
??? //根據(jù)ID查詢用戶
??? User selectUserById(int id);
}

????????????? 2.在UserMapper.xml 中添加相應(yīng)select 語句

<mapper namespace="com.xiezhr.dao.UserMapper">
???
??? <select id="selectUserById" parameterType="int" resultType="com.xiezhr.pojo.User">
??????? select * from mybatis.user where id = #{id}
??? </select>
</mapper>

????????????? 3.添加測試類

@Test
??? public void selectUserByid(){
??????? SqlSession sqlSession = MysqlUtil.getSqlSession();
??????? UserMapper mapper = sqlSession.getMapper(UserMapper.class);
??????? User user = mapper.selectUserById(1);
??????? System.out.println(user);
??? }

==測試通過==

User{id=1, name='張三', pwd='322334'}

????????????? 根據(jù)用戶姓名密碼查詢用戶信息

????????????? 1.在UserMapper接口中添加方法

public interface UserMapper {
??? //根據(jù)用戶名密碼查詢用戶信息
??? User selectUserByNP(@Param("name") String name,@Param("pwd") String pwd);
}

????????????? 2.在UserMapper.xml 中添加select語句

<mapper namespace="com.xiezhr.dao.UserMapper">
??? <select id="selectUserByNP" resultType="com.xiezhr.pojo.User">
??????? select * from mybatis.user where name=#{name} and pwd=#{pwd}
??? </select>
</mapper>

????????????? 3.添加測試類

??? @Test
??? public void selectUserByNP(){
??????? SqlSession sqlSession = MysqlUtil.getSqlSession();
??????? UserMapper mapper = sqlSession.getMapper(UserMapper.class);
??????? User user = mapper.selectUserByNP("張三","322334");
??????? System.out.println(user);

??? }

==測試成功==

User{id=1, name='張三', pwd='322334'}

以上通過用戶名和密碼查詢用戶,傳參還可以通過萬能的map實(shí)現(xiàn),具體代碼如下

????????????? 1.向UserMapper接口中添加方法

public interface UserMapper {
??? //根據(jù)用戶名和密碼查詢用戶信息
??? User queryUserByNP(Map<String,Object> map);
}

????????????? 2.向UserMapper.xml 中添加select語句,其中參數(shù)類型為map

<mapper namespace="com.xiezhr.dao.UserMapper">

??? <select id="queryUserByNP" parameterType="map" resultType="com.xiezhr.pojo.User">
??????? select * from mybatis.user where name=#{name} and pwd=#{pwd}
??? </select>
</mapper>

????????????? 添加測試,在使用過程中,map的key對應(yīng)著UserMapper.xml中取值,map在put值時(shí)候沒有先后順序

?@Test
??? public void queryUserByNp(){
??????? SqlSession sqlSession = MysqlUtil.getSqlSession();
??????? UserMapper mapper = sqlSession.getMapper(UserMapper.class);
??????? Map<String,Object> map = new HashMap<String,Object>();
??????? map.put("name","張三");
??????? map.put("pwd","322334");
??????? User user = mapper.queryUserByNP(map);
??????? System.out.println(user);
??? }

????????????? 模糊查詢實(shí)現(xiàn)

????????????? 1.在Java代碼中添加sql通配符

string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);

<select id=”selectlike”>
select * from foo where bar like #{value}
</select>

????????????? 2.在sql語句中拼接通配符,會(huì)引起sql注入

string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);

<select id=”selectlike”>
??? select * from foo where bar like "%"#{value}"%"
</select>


insert、update、delete

insert

1.????????? 在之前編寫的UserMapper 接口中添加增加方法

public interface UserMapper {
??? //添加一條用戶信息
??? int addUser(User user);
}

2.在UserMapper.xml 中寫insert 語句

<insert id="addUser" parameterType="com.xiezhr.pojo.User">
??????? insert into mybatis.user values(#{id},#{name},#{pwd})
</insert>

1.????????? 添加測試類
==insert、update、delete 一定要提交事務(wù),千萬千萬不能忘記了==

@Test
??? public void addUser(){
??????? SqlSession sqlSession = MysqlUtil.getSqlSession();
??????? UserMapper mapper = sqlSession.getMapper(UserMapper.class);

??????? User user = new User(4, "大頭兒子", "123456");
??????? mapper.addUser(user);
??????? sqlSession.commit();? //增刪改一定要提交事務(wù)
??????? sqlSession.close();
??? }

update

1.????????? 在之前編寫的UserMapper 接口中添加update方法

public interface UserMapper {
??? //修改一條記錄
??? int updateUserById(int id);
}

2.在UserMapper.xml 中寫insert 語句

<update id="updateUserById" parameterType="int">
??????? update mybatis.user set name='小頭爸爸' where id=#{id}
</update>

1.????????? 添加測試類
==insert、update、delete 一定要提交事務(wù),千萬千萬不能忘記了==

??? @Test
??? public void updateUserById(){
??????? SqlSession sqlSession = MysqlUtil.getSqlSession();
??????? UserMapper mapper = sqlSession.getMapper(UserMapper.class);
??????? mapper.updateUserById(4);
??????? sqlSession.commit();? //增刪改一定要提交事務(wù)
??????? sqlSession.close();
??? }

delete

1.????????? 在之前編寫的UserMapper 接口中添加delete方法

public interface UserMapper {
??? //根據(jù)ID刪除一條記錄
??? int deleteUserById(int id);
}
}

2.在UserMapper.xml 中寫insert 語句

<delete id="deleteUserById" parameterType="int">
??????? delete from mybatis.user where id=#{id}
</delete>

1.????????? 添加測試類
==insert、update、delete 一定要提交事務(wù),千萬千萬不能忘記了==

??? @Test
??? public void deletUserById(){
??????? SqlSession sqlSession = MysqlUtil.getSqlSession();
??????? UserMapper mapper = sqlSession.getMapper(UserMapper.class);
??????? mapper.deleteUserById(4);
??????? sqlSession.commit();? //增刪改一定要提交事務(wù)
??????? sqlSession.close();
??? }

注意

????????????? 所有的insert、update、delete 必須要提交事務(wù)

????????????? 接口中所有的普通參數(shù)盡量寫上@Param 參數(shù),尤其是多個(gè)參數(shù)的時(shí)候一定要寫上

????????????? 有些時(shí)候由于業(yè)務(wù)需要需要可通過map傳值

????????????? 為了規(guī)范在sql配置文件中即本例的UserMapper.xml 中select inset delete update 盡量寫上Parameter參數(shù)和resultType

可能出現(xiàn)問題說明:Maven靜態(tài)資源過濾問題

<build>
??????? <resources>
??????????? <resource>
??????????????? <directory>src/main/java</directory>
??????????????? <includes>
??????????????????? <include>**/*.properties</include>
??????????????????? <include>**/*.xml</include>
??????????????? </includes>
??????????????? <filtering>false</filtering>
??????????? </resource>
??????????? <resource>
??????????????? <directory>src/main/resources</directory>
??????????????? <includes>
??????????????????? <include>**/*.properties</include>
??????????????????? <include>**/*.xml</include>
??????????????? </includes>
??????????????? <filtering>false</filtering>
??????????? </resource>
??????? </resources>
??? </build>

在靜態(tài)資源的過濾中,基本的元素有三種:

????????????? directory:指定資源所在的目錄,這個(gè)目錄的路徑是相對于pom.xml文件;

????????????? includes:指定要包含哪些文件,其中包括inlcude子節(jié)點(diǎn)來指定匹配的模式;

????????????? excludes:指定要排除哪些文件,其中包括exclude子節(jié)點(diǎn)來指定匹配的模式;

????????????? filtering:指定哪些文件需要過濾,這個(gè)過濾的目的是為了替換其中的占位符${},其中的占位符屬性在pom.xml文件中的中指定;


第一個(gè)mybatis程序,實(shí)現(xiàn)增刪改查CRUD的評(píng)論 (共 條)

分享到微博請遵守國家法律
古丈县| 沙坪坝区| 灌阳县| 西平县| 聂荣县| 海兴县| 疏勒县| 犍为县| 玛曲县| 全州县| 白河县| 平凉市| 西平县| 青海省| 油尖旺区| 宁河县| 吴川市| 澎湖县| 云和县| 宁津县| 和静县| 宜州市| 普定县| 青浦区| 罗定市| 临湘市| 榆社县| 万山特区| 朝阳区| 白河县| 即墨市| 漠河县| 登封市| 金阳县| 正宁县| 广安市| 迭部县| 津南区| 新巴尔虎左旗| 宣威市| 聂荣县|