java 单独使用 mybaties 连接数据库(非web)

1.项目文件数据结构,项目由maven构建

pom.xml需要引入相关jar包

<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

source文件夹下为mybaities,数据库配置文件

mysql.properties  常用的就下面的几种

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/anti?useUnicode\=true&characterEncoding\=utf8
jdbc.username=root
jdbc.password=root
jdbc.maxActive=10
jdbc.minIdle=5
jdbc.maxWait=50000

mybaties-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>
    <!-- 引入外部配置文件 -->
    <properties resource="mysql.properties"></properties>
     <!-- 为JAVA Bean起类别名 -->
    <typeAliases >
         <!-- 别名方式1,一个一个的配置 type中放置的是类的全路径,alias中放置的是类别名
         <typeAliase type="com.cy.mybatis.beans.UserBean" alias="UserBean"/>-->
         <!-- 别名方式2,自动扫描,将JAVA类的类名作为类的类别名 -->
         <package name="com.AntiUav.Gis.Dao"/>
    </typeAliases>
   
     <!-- 配置mybatis运行环境 -->
       <environments default="cybatis">
         <environment id="cybatis">
             <!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
             <transactionManager type="JDBC" />
             <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
             <!-- POOLED 表示支持JDBC数据源连接池 -->
             <!-- UNPOOLED 表示不支持数据源连接池 -->
             <!-- JNDI 表示支持外部数据源连接池 -->
             <dataSource type="POOLED">
                 <property name="driver" value="${jdbc.driver}" />
                 <property name="url" value="${jdbc.url}" />
                 <property name="username" value="${jdbc.username}" />
                 <property name="password" value="${jdbc.password}" />
             </dataSource>
         </environment>
     </environments> 
     <mappers>
         <!-- 告知映射文件方式1,一个一个的配置
         <mapper resource="com/cy/mybatis/mapper/UserMapper.xml"/>-->
         <!-- 告知映射文件方式2,自动扫描包内的Mapper接口与配置文件 -->
         <package name="com.AntiUav.Gis.Dao.Mapper"/>
     </mappers>
</configuration>

Dao文件下主要做与数据交互的逻辑。

DBLinke文件夹是做数据库连接

Mapper文件夹是具体查询的sql和mapper映射

Entity是数据库表对应的实体类,model

DataService就是相对web架构中的sevice层,为control层服务的。

MysqlTool,利用mybaties,这里采用单例模式,一个单体项目只需和数据库建立一次连接。(也可以用静态代码块实现,相对优劣,可以去查查单例和静态方法的区别)

package com.AntiUav.Gis.Dao.DBLink;

import java.io.Reader;
import java.sql.Connection;

import javax.management.RuntimeErrorException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.TransactionIsolationLevel;
/**
 * 多线程的单例模式,使用双重校验机制
 */
public class MysqlTool {
	public volatile static SqlSessionFactory sessionFactory;
	
	public static SqlSession getInstance() {
        if (sessionFactory == null)
            synchronized (MysqlTool.class) {
                if (sessionFactory == null) {
                	try {
            			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            		}catch (Exception e) {
            			System.out.println("数据库连接错误!");
            			e.printStackTrace();
            			//throw  new RuntimeErrorException( null, "连接mysql数据库错误");
            		}
                }
            }
        return sessionFactory.openSession();
    }
//	static {
//		try {
//			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//			
//		}catch (Exception e) {
//			System.out.println("数据库连接错误!");
//			e.printStackTrace();
//			//throw  new RuntimeErrorException( null, "连接mysql数据库错误");
//		}
//	}
//	
//	public static SqlSession getSession() {
//		return sessionFactory.openSession();
//	}
}

DataSevice下的linePointService也是采用单例实现的,静态实现的被注释掉了。这样可以保证访问这张表也是单例的。不同业务不同实现,不一定非要单例。

package com.AntiUav.Gis.Dao.DataService;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.AntiUav.Gis.Dao.DBLink.MysqlTool;
import com.AntiUav.Gis.Dao.Entity.LinePoint;
import com.AntiUav.Gis.Dao.Mapper.LinePointsMapper;


public class LinePointsService {
	private static SqlSession session ;
	private static LinePointsMapper mapper;
	private volatile static LinePointsService linePointsService;
	public LinePointsService()
	{
		session = MysqlTool.getInstance();
		mapper = session.getMapper(LinePointsMapper.class);
	}
	
	public static LinePointsService getInstance() {
        if (linePointsService == null)
            synchronized (LinePointsService.class) {
                if (linePointsService == null) {
                	linePointsService = new LinePointsService();
                }
            }
        return linePointsService;
    }
	
	public  List<LinePoint> getLine(int line) {
		try {
			List<LinePoint> pointsList = mapper.getLine(line);
			session.commit();
			return pointsList;
		} catch (Exception e) {
		e.printStackTrace();
			session.rollback();
		}
		return null;
	}
	
	public static void addLinePoint(LinePoint point) {
		try {
			mapper.addLinePoint(point);
			session.commit();
		} catch (Exception e) {
		e.printStackTrace();
			session.rollback();
		}
	}
	
	public void delLinePoint(int num) {
		try {
			mapper.delLinePoint(num);
			session.commit();
		} catch (Exception e) {
		e.printStackTrace();
			session.rollback();
		}
	}
	
	
	
//	static {
//		session = MysqlTool.getInstance();
//		mapper = session.getMapper(LinePointsMapper.class);
//	}
	
//	public static List<LinePoint> getLine(int line) {
//		try {
//			List<LinePoint> pointsList = mapper.getLine(line);
//			session.commit();
//			return pointsList;
//		} catch (Exception e) {
//		e.printStackTrace();
//			session.rollback();
//		}
//		return null;
//	}
//	
//	public static void addLinePoint(LinePoint point) {
//		try {
//			mapper.addLinePoint(point);
//			session.commit();
//		} catch (Exception e) {
//		e.printStackTrace();
//			session.rollback();
//		}
//	}
//	
//	public void delLinePoint(int num) {
//		try {
//			mapper.delLinePoint(num);
//			session.commit();
//		} catch (Exception e) {
//		e.printStackTrace();
//			session.rollback();
//		}
//	}
}

另外粘贴下相关的实体类,映射mapper,和sql吧

LinePoint

package com.AntiUav.Gis.Dao.Entity;

import java.io.Serializable;
import java.util.Date;

public class LinePoint implements Serializable{
   public int id;
   public String UUID ;
   public String courseId;
   public int head;
   public int flag;
   public int num;
   public int historyNum;
   public double pitch;
   public double tilt;
   public double distance;
   public double height;
   public double speed;
   public double direction;
   public Date time;
   public double lat;
   public double lng;
   public String getUUID() {
		return UUID;
	}
	public void setUUID(String uUID) {
		UUID = uUID;
	}
	public String getCourseId() {
		return courseId;
	}
	public void setCourseId(String courseId) {
		this.courseId = courseId;
	}
	public int getHead() {
		return head;
	}
	public void setHead(int head) {
		this.head = head;
	}
	public int getFlag() {
		return flag;
	}
	public void setFlag(int flag) {
		this.flag = flag;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public int getHistoryNum() {
		return historyNum;
	}
	public void setHistoryNum(int historyNum) {
		this.historyNum = historyNum;
	}
	public double getPitch() {
		return pitch;
	}
	public void setPitch(double pitch) {
		this.pitch = pitch;
	}
	public double getTilt() {
		return tilt;
	}
	public void setTilt(double tilt) {
		this.tilt = tilt;
	}
	public double getDistance() {
		return distance;
	}
	public void setDistance(double distance) {
		this.distance = distance;
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	public double getSpeed() {
		return speed;
	}
	public void setSpeed(double speed) {
		this.speed = speed;
	}
	public double getDirection() {
		return direction;
	}
	public void setDirection(double direction) {
		this.direction = direction;
	}
	public Date getTime() {
		return time;
	}
	public void setTime(Date time) {
		this.time = time;
	}
	public double getLat() {
		return lat;
	}
	public void setLat(double lat) {
		this.lat = lat;
	}
	public double getLng() {
		return lng;
	}
	public void setLng(double lng) {
		this.lng = lng;
	}
}

LinePointsMapper.xml

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.AntiUav.Gis.Dao.Mapper.LinePointsMapper">
	<!--目的:为dao接口方法提供sql语句配置 即针对dao接口中的方法编写我们的sql语句 -->
	<select id="getLine" parameterType="int"
		resultType="com.AntiUav.Gis.Dao.Entity.LinePoint">
		select * from LinePoints where num = #{num}
	</select>

	<insert id="addLinePoint"
		parameterType="com.AntiUav.Gis.Dao.Entity.LinePoint">
		insert into LinePoints(UUID ,coursedID,head,flag,
        num,historyNum,pitch,tilt,distance,height,speed,
        direction,time,lat,lng) 
        values(#{point.UUID},#{point.coursedID},#{point.head},#{point.flag},
        #{point.num},#{point.historyNum},#{point.pitch},#{point.tilt},#{point.distance},
        #{point.height},#{point.speed},#{point.direction},#{point.time},#{point.lat},
        #{point.lng})
	</insert>
	<delete id="delLinePoint" parameterType="int">
		delete from LinePoints where num=#{num}
	</delete>

</mapper>

LinePointsMapper.java

package com.AntiUav.Gis.Dao.Mapper;

import java.util.List;

import com.AntiUav.Gis.Dao.Entity.LinePoint;

public interface LinePointsMapper {
	
	public List<LinePoint> getLine(int num) ;
	
	public void addLinePoint(LinePoint point) ;
	
	public void delLinePoint(int num);
}

然后就是测试是否可以使用了

package com.AntiUav.Gis.GisView;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.AntiUav.Gis.Dao.DataService.LinePointsService;
import com.AntiUav.Gis.Dao.Entity.LinePoint;


public class testMysql {
	public static void main(String[] args) {
		LinePointsService l = LinePointsService.getInstance();
		List<LinePoint> pointsList = l.getLine(1);
		for (LinePoint linePoint : pointsList) {
			System.out.println(linePoint.getLat()+","+linePoint.getLng()+","+linePoint.getTime());
		}
}

另外附加redis的配置使用

redis-config.properties  主要是IP和port其它都没使用到

#redis单机配置
redis.pool.host=127.0.0.1
redis.pool.port=6379
#最大能够保持idel状态的对象数
redis.pool.maxIdle=100
#最大分配的对象数
redis.pool.maxTotal=6000
#等待可用连接的最大时间,单位是毫秒,默认值为-1,表示永不超时。
#如果超过等待时间,则直接抛出JedisConnectionException
redis.pool.maxWaitMillis=10000
redis.pool.timeOut=20
#多长时间检查一次连接池中空闲的连接
redis.pool.timeBetweenEvictionRunsMillis=30000
#空闲连接多长时间后会被收回
redis.pool.minEvictableIdleTimeMillis=30000
#当调用borrow Object方法时,是否进行有效性检查
#在borrow(用)一个jedis实例时,是否提前进行validate(验证)操作;
#如果为true,则得到的jedis实例均是可用的
redis.pool.testOnBorrow=true
########reids编码格式
redis.encode=utf-8
######缓存过期时间 秒  1000*60*60*24*7 七天
redis.expire=604800000
####是否开启Redis服务应用
redis.unlock=false

redis的连接,这里使用ResourceBundle.getBundle获取配置文件信息

package com.AntiUav.Gis.Dao.DBLink;

import java.util.ResourceBundle;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisTool {
	private volatile  static Jedis jedis;//非切片额客户端连接
    private static JedisPool jedisPool;//非切片连接池
	private static ResourceBundle resource;//配置文件资源
	private static String ip;
	private static int port;
	
	public static Jedis getInstance() {
        if (jedis == null)
            synchronized (RedisTool.class) {
                if (jedis == null) {
                	resource = ResourceBundle.getBundle("redis-config");
            		ip = resource.getString("redis.pool.host");
            		port = Integer.parseInt(resource.getString("redis.pool.port"));
            		initialPool(); 
            		jedis = jedisPool.getResource(); 
                }
            }
        return jedis;
    }
//	
//	static {
//		//获取配置文件资源
//		resource = ResourceBundle.getBundle("redis-config");
//		ip = resource.getString("redis.pool.host");
//		port = Integer.parseInt(resource.getString("redis.pool.port"));
//		initialPool();  
//	}
//	public static Jedis getJedis(){
//	return jedis;
//}
//
	private static void initialPool() {
		// 池基本配置 
        JedisPoolConfig config = new JedisPoolConfig(); 
        config.setMaxActive(20); 
        config.setMaxIdle(5); 
        config.setMaxWait(1000l); 
        config.setTestOnBorrow(false);
        jedisPool = new JedisPool(config,ip,port);
	}
	

    
}

比较有意思事是redis只能保存字符串,byte数据。而通常工程里都是类型数据。所以这里涉及到类数据的序列化。

所以数据序列化就有两种情况了,一种是转成json字符串,一种是转成byte数据。这两者有什么区别呢?如果工程项目涉及到超过一种语言,这里就有问题了,除了字符串是通用的,好多类型在不同语言里并不是通用的。这里就涉及到了byte[]数据解码转成类数据了。相对来说,把数据序列化成json数据保存,可以有效的保存数据的准确行,通常在不同语言环境的数据交互里,都是使用json数据类型进行传输。

好了,这里我们当然也选择类数据转json,有效的保证项目的扩展性。当然为了更加的通用,我们还需要使用泛型来表达我们存储的类数据。

package com.AntiUav.Gis.Dao.DataService;



import com.AntiUav.Gis.Dao.DBLink.RedisTool;
import com.AntiUav.Gis.Dao.Entity.LinePoint;
import com.AntiUav.Gis.Util.Util;

import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;

public class RedisService {
	private static  Jedis redis;
	private volatile static RedisService redisService;
	
	public RedisService() {
		redis = RedisTool.getInstance();
	}

	public static RedisService getInstance() {
        if (redisService == null)
            synchronized (RedisService.class) {
                if (redisService == null) {
                	redisService = new RedisService();
                }
            }
        return redisService;
    }

	public  void del(String key) {
		redis.del(key);
    }
	
	public <T> T getValue(String key,T t) {
		JSONObject jsonObject = JSONObject.fromObject(redis.get(key).toLowerCase());
		return (T) JSONObject.toBean(jsonObject, t.getClass());
	}
	
	public <T> void addValue(String key,T t) {
		redis.set(key,JSONObject.fromObject(t).toString());
	}
	
//	static {
//		redis = RedisTool.getInstance();
//  }
//	public static<T> T getValue(String key,T t) {
//		JSONObject jsonObject = JSONObject.fromObject(redis.get(key).toLowerCase());
//		return (T) JSONObject.toBean(jsonObject, t.getClass());
//	}
//	
//	public static<T> void addValue(String key,T t) {
//		redis.set(key,JSONObject.fromObject(t).toString());
//	}
}

这里要还有关注的是JSONObject的jar包选择,JSONObject.toBean(jsonObject, t.getClass())可以动态的生成指定的对象。

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier><!-- 指定jdk版本 -->
        </dependency>

最后附上  数据转成byte的序列化方法

//序列化 
    public static byte[] serialize(Object obj){
        ObjectOutputStream obi=null;
        ByteArrayOutputStream bai=null;
        try {
            bai=new ByteArrayOutputStream();
            obi=new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt=bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        	try {
        		obi.close();
        		bai.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        return null;
    }
    
    //反序列化
    public static Object unserizlize(byte[] data){
        ObjectInputStream oii=null;
        ByteArrayInputStream bis=null;
        Object obj = null;
        try {
        	bis=new ByteArrayInputStream(data);
            oii=new ObjectInputStream(bis);
            obj=oii.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        	try {
				oii.close();
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        
        return obj;
    }

猜你喜欢

转载自blog.csdn.net/ido1ok/article/details/85044110