美文网首页Java学习笔记
maven项目接入mybatis for mysql

maven项目接入mybatis for mysql

作者: 战五渣_lei | 来源:发表于2017-03-31 22:05 被阅读93次

    本文主要描述在ubuntu环境下 使用maven和idea构建mybatis项目,maven的配置相关见之前的博客

    1 安装 mysql

    ubuntu环境下mysql还是挺好安装的,teminal输入指令

    sudo apt-get install mysql-server
    sudo apt-get install mysql-client
    sudo apt-get install libmysqlclient-dev
    

    三行指令执行完,mysql就装好了
    然后输入

    mysql -u root -p
    

    然后输入你的mysql root 帐号密码就能登进去了。

    为了数据安全,需要创建一个非root帐号 ,用来实际操作数据库
    输入如下

    CREATE USER 'lei'@'localhost' IDENTIFIED BY '123456'; 
    

    意思就是创建一个 用户 帐号为 lei,只允许在本机登录,密码为123456

    然后我们可以建立一个数据库

    create database mystudy_db;
    use mystudy_db;
    

    这样就创建了一个名为mystudy_db的数据库,并且使用它
    然后授予lei用户若干权限

    grant select,update,insert on mystudy_db.* to lei@"localhost" identified by "123456";
    
    

    再在库中加入一张表,表名为t_student,只是测试用就简单一点,一个主键id,一个名字name

    create table  if not exists t_student  (id bigint primary key auto_increment,name varchar(25)  not null)engine=innodb auto_increment=1000 default charset = utf8;
    
    

    执行如上指令建表成功,并且效果如图

    建表成功

    然后我们插入几条数据用于测试

    mysql> insert into t_student (name) values('张老三')
    mysql> insert into t_student (name) values('王五')
    mysql> insert into t_student (name) values('王6')
    

    数据有了就开始玩mybais了

    2 使用idea maven 配置mybatis

    新建一个maven项目,因为后面是要做服务器的,所以建一个maven webapp 项目 ,具体操作见之前的博客
    关键是依赖和xml配置文件的编写
    项目自动构建好了以后,编辑pom 加入如下内容

    <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/maven-v4_0_0.xsd">
      。。。。。。。。
        <dependencies>
           。。。。。
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.25</version>
            </dependency>
        </dependencies>
        <build>
            <finalName>leitestaid</finalName>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    </project>
    
    

    dependency里面加入了 mybaits ,jdbc ,和 log4j,并且标记resources意思是编译输出会保留xml和properties文件,即保留配置文件,这点是非常重要的
    然后在 java根目录 src/main/java下加入log4j.properties,这是控制mybatis输出日志的还是有点用的

    #
    #    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.
    #
    
    ### Global logging configuration
    log4j.rootLogger=DEBUG, stdout
    
    ### Uncomment for MyBatis logging
    log4j.logger.org.apache.ibatis=DEBUG
    
    log4j.logger.org.apache.ibatis.session.AutoMappingUnknownColumnBehavior=WARN, lastEventSavedAppender
    
    ### 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
    
    log4j.appender.lastEventSavedAppender=org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$LastEventSavedAppender
    
    

    下一步是引入xml文件,就是数据库的映射关系
    在java的任意包下写这个配置文件 取名为MapperConfig.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>
    
    
    
      <typeAliases>
    
      </typeAliases>
    
    
    
    
      <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC">
            <property name="" value=""/>
          </transactionManager>
          <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mystudy_db"/>
            <property name="username" value="lei"/>
            <property name="password" value="123456"/>
          </dataSource>
        </environment>
      </environments>
      
    
    
      <mappers>
        <mapper resource="com/lei/mapper/AuthorMapper.xml"/>
    
      </mappers>
    
    </configuration>
    
    

    然后编辑数据库映射文件 取名为AuthorMapper.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="com.lei.testr">
    
    
        <select id="getAllStudent" resultType="com.lei.model.Student">
            select * from t_student
        </select>
    
    
    </mapper>
    

    这样xm文件也配好了
    我们的model类student 如下

    package com.lei.model;
    
    import org.apache.ibatis.annotations.MapKey;
    
    /**
     * Created by ylei on 17-3-31.
     */
    public class Student {
    
        long id;
        String name;
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
    

    这样开始测试吧,代码如下

    package com.lei.test;
    
    import com.lei.model.Student;
    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;
    import java.util.List;
    
    /**
     * Created by ylei on 17-3-31.
     */
    public class FirstMyBatis {
    
        public static void main(String[]args){
            Reader reader=null;
            SqlSessionFactory ssf=null;
            SqlSession session=null;
            try {
                reader= Resources.getResourceAsReader("com/lei/mapper/MapperConfig.xml");
                SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
                ssf= sqlSessionFactoryBuilder.build(reader);
                session=ssf.openSession();
               List<Student> students= session.selectList("getAllStudent");
                for (Student student : students) {
                    System.out.println("学生 id"+student.getId()+"\t 名字:"+student.getName());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                session.close();
            }
        }
    }
    
    

    run一下
    控制台打印如图 ,可能log4j会输出一些错误,但是不影响主流程

    idea输出成功

    相关文章

      网友评论

        本文标题:maven项目接入mybatis for mysql

        本文链接:https://www.haomeiwen.com/subject/qftbottx.html