java+maven+sqlserver使用mybatis

Posted 张亚南

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java+maven+sqlserver使用mybatis相关的知识,希望对你有一定的参考价值。

第一部分:基本实现

@参考文章,在此基础上略作修改

1,新建maven项目JavaMybatis导入依赖

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency>
    </dependencies>
View Code

2,com.mybatis包下新建Yanan.java

package com.mybatis;

public class Yanan {
    private int iid;
    private String ifullname;
    private String iloginname;
    private String ipassword;

    public Yanan() {
    }

    public Yanan(int id, String name) {
        this.iid = id;
        this.ifullname = name;
    }

    public String getIfullname() {
        return ifullname;
    }

    public int getIid() {
        return iid;
    }

    public void setIid(int iid) {
        this.iid = iid;
    }

    public void setIfullname(String ifullname) {
        this.ifullname = ifullname;
    }

    public String getIloginname() {
        return iloginname;
    }

    public void setIloginname(String iloginname) {
        this.iloginname = iloginname;
    }

    public String getIpassword() {
        return ipassword;
    }

    public void setIpassword(String ipassword) {
        this.ipassword = ipassword;
    }
}
View Code

3,根目录下新建Yanan.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="Yanan">    
    <select id="selectUser" parameterType="int" resultType="Yanan">    
        SELECT * FROM Yanan WHERE id = #{id}    
    </select>    
        
    <select id="selectUsers" resultType="Yanan">    
        SELECT * FROM Yanan    
    </select>    
        
</mapper>
View Code

4,根目录下新建configuration.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>    
    <typeAliases>    
        <typeAlias alias="Yanan" type="com.mybatis.Yanan"></typeAlias>    
    </typeAliases>    
        
    <environments default="development">    
        <environment id="development">    
            <transactionManager type="JDBC"></transactionManager>    
            <dataSource type="POOLED">    
                <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />    
                <property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=test" />    
                <property name="username" value="sa" />    
                <property name="password" value="yanan" />    
            </dataSource>    
        </environment>    
    </environments>    
        
    <mappers>    
        <mapper resource="Yanan.xml"/>    
    </mappers>    
    
</configuration>
View Code

5.com.controller包下新建测试文件

package com.controller;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

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 com.mybatis.Yanan;

public class Test {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String resource = "configuration.xml";    
        Reader reader = Resources.getResourceAsReader(resource);    
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);    
        SqlSession session = ssf.openSession();    
        try{    
            Yanan user = session.selectOne("selectUser", 1);    
            System.out.println(user.getIfullname());    
            System.out.println(user);    
            System.out.println("--------------分隔线---------------");    
            
            List<Yanan> users = session.selectList("selectUsers");    
            for(int i=0; i<users.size(); i++) {    
                System.out.println(users.get(i).getIfullname());    
            }    
                
        } catch (Exception e) {    
            e.printStackTrace();    
        } finally {    
            session.close();    
        }    
    }

}
View Code

源码包下载:JavaMybatis.rar

建表语句:

/*
Navicat SQL Server Data Transfer

Source Server         : .
Source Server Version : 105000
Source Host           : .:1433
Source Database       : test
Source Schema         : dbo

Target Server Type    : SQL Server
Target Server Version : 105000
File Encoding         : 65001

Date: 2018-09-04 13:49:17
*/


-- ----------------------------
-- Table structure for yanan
-- ----------------------------
DROP TABLE [dbo].[yanan]
GO
CREATE TABLE [dbo].[yanan] (
[id] int NOT NULL IDENTITY(1,1) ,
[ifullname] varchar(255) NULL ,
[iloginname] varchar(255) NULL ,
[ipassword] varchar(255) NULL 
)


GO

-- ----------------------------
-- Records of yanan
-- ----------------------------
SET IDENTITY_INSERT [dbo].[yanan] ON
GO
INSERT INTO [dbo].[yanan] ([id], [ifullname], [iloginname], [ipassword]) VALUES (N\'1\', N\'sd\', N\'fd\', N\'sd\')
GO
GO
SET IDENTITY_INSERT [dbo].[yanan] OFF
GO

-- ----------------------------
-- Indexes structure for table yanan
-- ----------------------------

-- ----------------------------
-- Primary Key structure for table yanan
-- ----------------------------
ALTER TABLE [dbo].[yanan] ADD PRIMARY KEY ([id])
GO
View Code

 

项目结构展示:

 

 

第二部分:改造优化

上述方式能实现,但需要建实体类,影响开发和维护效率,下面改造成接口形式且无实体类方式:

为了便于区分(也便于我接下来的项目),把名称结构等做了修改

1,同上(项目名DeleteOrder)

2,cn.yanan.deleteorder.mapper下新建UserMapper接口

package cn.yanan.deleteorder.mapper;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    Map<String,Object> selectUser(int id);
    List<Map<String,Object>> selectUsers();
}
View Code

3,根目录下新建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="cn.yanan.deleteorder.mapper.UserMapper">    
    <select id="selectUser" parameterType="int" resultType="java.util.Map">    
        SELECT * FROM Yanan WHERE id = #{id}    
    </select>    
        
    <select id="selectUsers" resultType="java.util.Map">    
        SELECT * FROM Yanan    
    </select>    
        
</mapper>
View Code

4,根目录下新建configuration.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>    
    <environments default="development">    
        <environment id="development">    
            <transactionManager type="JDBC"></transactionManager>    
            <dataSource type="POOLED">    
                <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />    
                <property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=test" />    
                <property name="username" value="sa" />    
                <property name="password" value="yanan" />    
            </dataSource>    
        </environment>    
    </environments>    
        
    <mappers>    
        <mapper resource="UserMapper.xml"/>    
    </mappers>    
    
</configuration>
View Code

5,cn.yanan.deleteorder.controller包下新建测试文件

package cn.yanan.deleteorder.controller;

import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;

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 cn.yanan.deleteorder.mapper.UserMapper;

public class MainController {
    public static void main(String[] args) throws IOException {
        String resource = "configuration.xml";    
        Reader reader = Resources.getResourceAsReader(resource);    
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);    
        SqlSession session = ssf.openSession();    
        try{    
            UserMapper mapper = session.getMapper(UserMapper.class);
            Map<String,Object> user = mapper.selectUser(1);
            List<Map<String,Object>> users = mapper.selectUsers();
            System.out.println(user.get("ifullname"));    
            System.out.println(user);    
            System.out.println("--------------分隔线---------------");      
            for(int i=0; i<users.size(); i++) {    
                System.out.println(users.get(i).get("ifullname"));    
            }    
        } catch (Exception e) {    
            e.printStackTrace();    
        } finally {    
            session.close();    
        }    
    }
}
View Code

 

源码包下载:DeleteOrder.rar

 

建表语句:同上

 项目结构展示:

 

第三部分:继续优化

经过第二部分的优化已经能满足大部分网友的需求了。但对于一些要将该项目导出可运行jar包的网友来说并不能很好地运行,摘自一位博客的说法:

“因为”…/ResourceJar.jar!/resource/….”并不是文件资源定位符的格式 (jar中资源有其专门的URL形式: jar:!/{entry} )”,详细论述@参考博客

所以我们使用如下的方式:

InputStream is=MainController.class.getResourceAsStream("/configuration.xml");   
BufferedReader br=new BufferedReader(new InputStreamReader(is));

经过上述步骤你会发现在eclipse下能够正常运行,但jar包还不能加载到配置文件,我们继续进行改造

src同目录下建资源包,并把配置文件拖拽进去,结构如下(上述.getResourceAsStream("/configuration.xml")配置不变)

如此,eclipse中与jar包中都能加载到配置文件了。但此时你会发现新的异常,加载不到configuration中的mapper.xml文件

我们继续改造,打开configuration.xml进行配置

 

 并将此二者拖拽到configuration.xml同目录下:

至此,大事告成!

此时博主已整合了大量项目业务,不便将源码包发给大家,思路有了,我也写的很清晰,读者自行整理吧

以上是关于java+maven+sqlserver使用mybatis的主要内容,如果未能解决你的问题,请参考以下文章

java 后台框架 支持APP接口调用 APP后台 手机后台框架java springmvc myb

错误org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.baomidou.myb

Maven下创建SSM项目的所有依赖和插件

Mybaits 快速入门代码实例(maven代码版)

带有 docker 容器的 bitbucket 管道

Mybatis基本使用