服务器之家

服务器之家 > 正文

mybatis实现增删改查_动力节点Java学院整理

时间:2020-12-26 15:25     来源/作者:动力节点

所需要用到的其他工具或技术:

项目管理工具 : Maven

测试运行工具 : Junit

数据库 : Derby

Maven Dependencies:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.7</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.9</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derby</artifactId>
      <version>10.10.2.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derbyclient</artifactId>
      <version>10.10.2.0</version>
    </dependency>
  </dependencies>

SQL 建表及数据插入(沿用前两节中的数据库表及数据):

?
1
2
3
4
5
6
7
8
9
CREATE TABLE USER_TEST_TB( 
ID INT PRIMARY KEY, 
USERNAME VARCHAR(20) NOT NULL, 
PASSWORD VARCHAR(20) NOT NULL, 
NICKNAME VARCHAR(20) NOT NULL 
);   
INSERT INTO USER_TEST_TB VALUES(1,'1st','111','Jack'); 
INSERT INTO USER_TEST_TB VALUES(2,'2nd','222','Rose'); 
INSERT INTO USER_TEST_TB VALUES(3,'3rd','333','Will');

Mybatis配置文件 src/main/resource源目录下

test-mybatis-configuration.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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>
  <properties>
    <property name="driver" value="org.apache.derby.jdbc.ClientDriver" />
    <property name="url"
      value="jdbc:derby://localhost:1527/bjpowernode;create=true" />
  </properties>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED">
        <property name="driver" value="${driver}" />
        <property name="url" value="${url}" />
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/bjpowernode/practice/UserMapper.xml" /
  </mappers>
</configuration>

 User.java对象类(src/main/java/com/bjpowernode/practice目录下)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.bjpowernode.practice; 
public class User
{
  private Integer id;
  private String username;
  private String password;
  private String nickname;
  public Integer getId()
  {
    return id;
  }
  public void setId(Integer 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;
  }
  public String getNickname()
  {
    return nickname;
  }
  public void setNickname(String nickname)
  {
    this.nickname = nickname;
  }
}

UserMapper.xml  Mapper文件(src/main/java/com.bjpowernode.practice目录下)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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.bjpowernode.practice.UserMapper">
  <!-- 查询 -->
  <select id="getUser" resultType="com.bjpowernode.practice.User">
    select *
    from USER_TEST_TB
  </select>
  <!-- 插入 -->
  <insert id="insertUser">
    insert into 
      USER_TEST_TB 
    values(#{id},#{username},#{password},#{nickname})
  </insert>
  <!-- 更改 -->
  <update id="updateUser">
    update USER_TEST_TB set
      USERNAME = #{username},
      PASSWORD = #{password},
      NICKNAME = #{nickname}
    where ID = #{id}
  </update>
  <!-- 删除 -->
  <delete id="deleteUser">
    delete from USER_TEST_TB WHERE ID=#{id}
  </delete>
</mapper>

UserMapper.java Mapper类(src/main/java/com.bjpowernode.practice目录下)

?
1
2
3
4
5
6
7
8
9
package com.bjpowernode.practice;
import java.util.List;
public interface UserMapper
{
  public List<User> getUser();
  public void insertUser(User user);
  public void updateUser(User user);
  public void deleteUser(int userId);
}

测试类TestMyBatis.java(src/test/java/com.bjpowernode.practice目录下)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package com.bjpowernode.practice; 
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
public class TestMyBatis
{
  private String source;
  private InputStream inputStream;
  private SqlSessionFactory sqlSessionFactory;
  @Before
  public void setUp()
  {
    /**
     * 准备Mybatis运行环境
     */
    source = "test-mybatis-configuration.xml";
    inputStream = TestMyBatis.class.getClassLoader().getResourceAsStream(source);
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  }
  @Test
  public void testGet()
  {
    try
    {
      // 获取Session连接
      SqlSession session = sqlSessionFactory.openSession();
      // 获取Mapper
      UserMapper userMapper = session.getMapper(UserMapper.class);
      // 显示User信息
      System.out.println("Test Get start...");
      this.printUsers(userMapper.getUser());
      System.out.println("Test Get finished...");
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  @Test
  public void testInsert()
  {
    try
    {
      // 获取Session连接
      SqlSession session = sqlSessionFactory.openSession();
      // 获取Mapper
      UserMapper userMapper = session.getMapper(UserMapper.class);
      System.out.println("Test insert start...");
      // 显示插入之前User信息
      System.out.println("Before insert");
      this.printUsers(userMapper.getUser());
      // 执行插入
      userMapper.insertUser(this.mockUser("FREU_INS_USER", "BJPOWERNODE_INS_PASS", "BJPOWERNODE_INS_NICK"));
      // 提交事务
      session.commit();
      // 显示插入之后User信息
      System.out.println("\r\nAfter insert");
      this.printUsers(userMapper.getUser());
      System.out.println("Test insert finished...");
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  @Test
  public void testUpdate()
  {
    try
    {
      // 获取Session连接
      SqlSession session = sqlSessionFactory.openSession();
      // 获取Mapper
      UserMapper userMapper = session.getMapper(UserMapper.class);
      System.out.println("Test update start...");
      // 显示更新之前User信息
      System.out.println("Before update");
      this.printUsers(userMapper.getUser());
      // 执行更新
      userMapper.updateUser(this.mockUser("FREU_UPD_USER", "BJPOWERNODE_UPD_PASS", "BJPOWERNODE_UPD_NICK"));
      // 提交事务
      session.commit();
      // 显示更新之后User信息
      System.out.println("\r\nAfter update");
      this.printUsers(userMapper.getUser());
      System.out.println("Test update finished...");
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  @Test
  public void testDelete()
  {
    try
    {
      // 获取Session连接
      SqlSession session = sqlSessionFactory.openSession();
      // 获取Mapper
      UserMapper userMapper = session.getMapper(UserMapper.class);
      System.out.println("Test delete start...");
      // 显示删除之前User信息
      System.out.println("Before delete");
      this.printUsers(userMapper.getUser());
      // 执行删除
      userMapper.deleteUser(this.mockUser(null, null, null).getId());
      // 提交事务
      session.commit();
      // 显示删除之后User信息
      System.out.println("\r\nAfter delete");
      this.printUsers(userMapper.getUser());
      System.out.println("Test delete finished...");
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  /**
   *
   * 组装一个User对象
   *
   * @return
   */
  public User mockUser(String username, String password, String nickname)
  {
    User user = new User();
    user.setId(10);
    user.setUsername(username);
    user.setPassword(password);
    user.setNickname(nickname);
    return user;
  }
  /**
   *
   * 打印用户信息到控制台
   *
   * @param users
   */
  private void printUsers(final List<User> users)
  {
    int count = 0;
    for (User user : users)
    {
      System.out.println(MessageFormat.format("==User[{0}]=================", ++count));
      System.out.println("User Id: " + user.getId());
      System.out.println("User UserName: " + user.getUsername());
      System.out.println("User Password: " + user.getPassword());
      System.out.println("User nickname: " + user.getNickname());
    }
  }
}

总结

以上所述是小编给大家介绍的mybatis实现增删改查_动力节点Java学院整理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
返回顶部