码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis入门-1

时间:2019-10-23 11:16:23      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:exist   char   ble   数据库表   map   thread   doc   star   理解   

MyBatis中文官网:
http://www.mybatis.cn/

我使用的工具是idea,jdk是1.8

1.创建一个maven项目 mbs_maven

技术图片

 

 

 2.引入mybatis的jar包

 1         <dependency>
 2             <groupId>mysql</groupId>
 3             <artifactId>mysql-connector-java</artifactId>
 4             <version>5.1.46</version>
 5         </dependency>
 6 
 7         <dependency>
 8             <groupId>org.mybatis</groupId>
 9             <artifactId>mybatis</artifactId>
10             <version>3.5.1</version>
11         </dependency>    

3.引入log的jar包,mybatis是需要依赖log ,引入junit测试和lobok代码简化工具

 1         <dependency>
 2             <groupId>org.projectlombok</groupId>
 3             <artifactId>lombok</artifactId>
 4             <version>1.18.10</version>
 5         </dependency>
 6 
 7         <!-- log start -->
 8         <dependency>
 9             <groupId>org.slf4j</groupId>
10             <artifactId>slf4j-api</artifactId>
11             <version>${slf4j-api.version}</version>
12         </dependency>
13         <dependency>
14             <groupId>ch.qos.logback</groupId>
15             <artifactId>logback-core</artifactId>
16             <version>${logback.version}</version>
17         </dependency>
18         <dependency>
19             <groupId>ch.qos.logback</groupId>
20             <artifactId>logback-access</artifactId>
21             <version>${logback.version}</version>
22         </dependency>
23         <dependency>
24             <groupId>ch.qos.logback</groupId>
25             <artifactId>logback-classic</artifactId>
26             <version>${logback.version}</version>
27         </dependency>
28         <!-- log end -->
29 
30         <dependency>
31             <groupId>junit</groupId>
32             <artifactId>junit</artifactId>
33             <version>4.12</version>
34         </dependency>
1     <properties>
2         <slf4j-api.version>1.7.25</slf4j-api.version>
3         <logback.version>1.1.7</logback.version>
4     </properties>

4.创建logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoder 默认配置为PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>
    <logger name="dao" level="DEBUG"/>
    <!--自己的dao层-->
    <logger name="cm.mbs.dao" level="INFO"/>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

5.创建mybatis-config.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>
    <!--使用logback的配置-->
    <settings>
        <setting name="logPrefix" value="dao." />
    </settings>
    <!--<settings>-->
        <!--&lt;!&ndash; 指定使用LOG4J输出日志 &ndash;&gt;-->
        <!--<setting name="logImpl" value="LOG4J"/>-->
    <!--</settings>-->
    <typeAliases>
        <!-- 配置包的别名,通常在使用类时需要使用类的全限定名称,使用该配置后只要直接使用类名即可 -->
        <package name="cm.mbs.entity"/>
    </typeAliases>

    <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?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 在src/main/resources目录下创建mapper目录 -->
        <mapper resource="mapper/UserMapper.xml" />
    </mappers>
</configuration>

6.创建数据库表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `password` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `age` int(10) DEFAULT NULL,
  `sex` int(2) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `created` datetime(0) DEFAULT NULL,
  `updated` datetime(0) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES (1, zs, 123456, 张三, 22, 1, 1990-09-02, 2019-10-22 11:07:19, 2019-10-22 11:07:19);
INSERT INTO `tb_user` VALUES (2, ls, 123456, 李四, 23, 1, 1993-09-05, 2019-10-22 11:07:19, 2019-10-22 11:07:19);
INSERT INTO `tb_user` VALUES (3, ww, 123456, 王五, 24, 1, 1990-09-09, 2019-10-22 12:32:04, 2019-10-22 12:32:04);

SET FOREIGN_KEY_CHECKS = 1;

7.创建实体类

@Data  //这个是lombok的注解,为每一个私有属性创建get set方法
@NoArgsConstructor  //lombok 无参构造器
public class User {

    private Long id;
    private String userName;
    private String password;

}

8.创建dao

public interface UserMapper {

    List<User> selectAll();

}

9.创建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="cm.mbs.dao.UserMapper">

    <select id="selectAll" resultType="User">

        select Id,UserName,Password from t_user

    </select>

</mapper>

10.编写测试类

public class UserMapperTest {

    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init() {
        InputStream is = null;
        try {
            String resource = "mybatis-config.xml";
            is = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testSelectAll() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            List<User> list = sqlSession.selectList("selectAll");
            for (User user : list) {
                System.out.println(user.getUserName() + "  " + user.getPassword());
            }
        }
    }

}

11.mybatis的启动理解

  1. 构建sqlSessionFactory (UserMapperTest.java)

// 指定全局配置文件
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream is = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

  2. 打开sqlSession对话,并执行sql (UserMapperTest.java)

 

// 获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 操作CRUD,指定statement,规则:命名空间+“.”+statementId
List<User> list = sqlSession.selectList("selectAll");
// 这个地方也可以使用 getMapper来获取mapper对象例如
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 执行查询方法
List<User> users = mapper.selectAll();

 

mybatis入门-1

标签:exist   char   ble   数据库表   map   thread   doc   star   理解   

原文地址:https://www.cnblogs.com/L-o-g-i-c/p/11724844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!