栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

用maven和mybatis连接数据库的简单例子

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用maven和mybatis连接数据库的简单例子

无数个bug我调了两个小时。
第一步,创建一个maven项目。






第一步结束,maven项目构建成功。

第二步,利用pom.xml配置文件安装一些必要的依赖。
您可以访问maven repository网站下载,也可以复制我的。


    
      junit
      junit
      4.11
      test
    
    
    
    
      mysql
      mysql-connector-java
      5.1.47
    
    
    
      org.mybatis
      mybatis
      3.5.7
    

    
    
    
      cglib
      cglib
      3.3.0
    
    
    
      commons-logging
      commons-logging
      1.2
    

    
    
      ognl
      ognl
      3.2.20
    
    
    
      org.apache.logging.log4j
      log4j-core
      2.14.1
    
    
    
      org.javassist
      javassist
      3.27.0-GA
    
    
    
      org.slf4j
      slf4j-api
      1.7.30
    
    
    
      org.slf4j
      slf4j-log4j12
      1.7.30
      test
    
    
      junit
      junit
      4.12
      compile
    

    
      log4j
      log4j
      1.2.17
    

  

依赖复制之后,在左侧菜单栏会有对应的包被下载好。

注意,第一是容易报错的log4j问题,因为我第一次运行的时候报错说没有这个包,所以我特意上网找办法,写了一个java文件导入它,但我现在找不到相关链接了,把代码贴过来吧。
(注意,如果你最后没有报log4j的错,就不用写这个文件了)

public class initLogRecord{
        public static void initLog() {
            FileInputStream fileInputStream = null;
            try {
                Properties properties = new Properties();
                fileInputStream = new FileInputStream("src/main/resources/log4j.properties");
                //这个log4j.properties我会贴下面
                properties.load(fileInputStream);
                PropertyConfigurator.configure(properties);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }



log4j.properties:

# Global logging configuration
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

这个文件放到"src/main/resources/log4j.properties"这个目录。

下面:
1.在src文件夹下新建main文件夹,再在main文件夹下新建resources文件夹,并把它设为Resources Root

在resources下新建2个文件和一个文件夹,分别是configuration.xml,
db.properties,和mappers(这是个文件夹)

configuration.xml内容:





    
    

    

    
        
        
        
        
        
        
        
        
    

    
        
        
        
    

    
    
        
            
            
            
            
                
                
                
                
                
                
                
            
        


    

    
        
    

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
//mysql8用这个:
//?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
password=0711

test.driver=com.mysql.jdbc.Driver
test.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
test.username=root
test.password=0711

这里面就包括url,username和password,端口3306后面跟的是数据库的名字,也就是说你想查的这个表属于哪个数据库你就写哪个库的名字

接着在src下的main下新建文件夹java并将它设置为sources root
在java下新建edu.hrbeu.dao,同级的还有db和entity

在dao目录下新建接口类WebsiteMapper

package edu.hrbeu.dao;

import edu.hrbeu.entity.Website;

import java.util.List;


public interface WebsiteMapper {
    
    Website findByPrimaryKey(int id);

    
    List findLikeName(String name);

    
    int insert(Website website);

    
    int update(Website website);

    
    int delete(int id);

}


在db文件夹下新建DBUtils.java类

package edu.hrbeu.db;

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;


public class DBUtils {
    //实例化数据库会话工厂类
    static SqlSessionFactory factory;
    static {

        try {
            //加载主配置文件
            Reader reader = Resources.getResourceAsReader("configuration.xml");
            //创建工厂对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(reader, "mysql0711");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
        public static SqlSession getSession(){
            return factory.openSession();
        }
        public static void close(SqlSession sqlSession){
            sqlSession.close();
        }

    }


在entity文件夹下新建Website类,它对应了一张数据库表

package edu.hrbeu.entity;
//站点实体类--表websites

public class Website {
     private int id;
     private String name;
     private String url;
     private int alexa;
     private String country;

     public Website(){}

    public Website(int id, String name, String url, int alexa, String country) {
        this.id = id;
        this.name = name;
        this.url = url;
        this.alexa = alexa;
        this.country = country;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getAlexa() {
        return alexa;
    }

    public void setAlexa(int alexa) {
        this.alexa = alexa;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "Website{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", url='" + url + ''' +
                ", alexa=" + alexa +
                ", country='" + country + ''' +
                '}';
    }
}

整体目录是这样的。

然后在src目录下新建一个用于测试的文件夹test

在test下也和main类似的构建目录

最下一级就是需要我们运行的测试类WebsiteMapperTest

package edu.hrbeu.dao;

import edu.hrbeu.db.DBUtils;
import edu.hrbeu.entity.Website;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;


public class WebSiteMapperTest {
    WebsiteMapper websiteMapper;
    @Before
    public void init(){
        SqlSession session = DBUtils.getSession();//获取一个会话
        websiteMapper = session.getMapper(WebsiteMapper.class);

    }
    @Test
    public void test01(){
        Website website = websiteMapper.findByPrimaryKey(1);
        System.out.println(website);
    }
}

点击代码test01旁边的绿色三角运行测试方法,观察输出结果:

忘了让您看看数据库的目录和内部数据了。
数据库的表名叫websites,你把他放哪个库里其实无所谓

这样就把id=1的数据整行读出来了

当然还有增删改之类的问题,我还没有学到,现在只是查。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/603399.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号