当前位置: 移动技术网 > IT编程>开发语言>Java > 浅析Mybatis 在CS程序中的应用

浅析Mybatis 在CS程序中的应用

2019年07月22日  | 移动技术网IT编程  | 我要评论

因为mybatis好使,所以几乎需要操作数据库的时候,我都会使用mybatis,而且在一个正式的项目中,同时存在bs和cs的程序,都使用的mybatis,使用的相同mapper文件。

mybatis的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" />
   <datasource type="pooled">
    <property name="driver" value="driver" />
    <property name="url" value="url" />
    <property name="username" value="username" />
    <property name="password" value="password" />
   </datasource>
  </environment>
 </environments>

 <mappers>
  <mapper resource="com/isea/dao/youmapper.xml" />
 </mappers>
</configuration>

为了防止数据库用户名密码泄漏,我将xml进行双向加密,变成了一个字节文件,而且文件名后缀随意。
例如:basic.data,内容局部如下:

根据xml生成mybatis的sqlsessionfactory,代码如下:

复制代码 代码如下:

public class mybatis {
 private static final string config = "basic.data";
 private sqlsessionfactory sqlsessionfactory;

 private static mybatis instance = new mybatis();

 private mybatis(){
  inputstream inputstream = null;
  try {
   inputstream = getxmlis();
   if(inputstream==null){
    throw new runtimeexception("数据库信息配置失败!");
   }
   sqlsessionfactory = new sqlsessionfactorybuilder().build(inputstream);
  } finally{
   try {
    inputstream.close();
   } catch (exception e) {
   }
  }
 }

 public static inputstream getxmlis(){
  inputstream inputstream = null;
  try {
   //对资源进行加密,解密后处理
   bufferedreader reader = new bufferedreader(new filereader(new file(config.location+"/"+config)));
   string str = null;
   stringbuffer sbbuffer = new stringbuffer();
   while((str=reader.readline())!=null){
    sbbuffer.append(str);
   }
   encrypdes encrypdes = new encrypdes();
   string result = encrypdes.decryptor(sbbuffer.tostring());
   inputstream = new bytearrayinputstream(result.getbytes());
   return inputstream;
  } catch (exception e) {
  }
  return null;
 }

 public sqlsessionfactory getsqlsessionfactory(){
  return sqlsessionfactory;
 }

 public static mybatis getinstance(){
  return instance;
 }
}

这里的data文件是在src下。
代码中的encrypdes是一个使用des的加密解密类。
代码中的config.location代码如下:
复制代码 代码如下:

public static string getrealpath() throws exception {
  string realpath = config.class.getclassloader().getresource("").getfile();
  java.io.file file = new java.io.file(realpath);
  realpath = file.getabsolutepath();
  realpath = java.net.urldecoder.decode(realpath, "utf-8");
  return realpath;
 }

getrealpath()返回的值赋给location.

上面代码的主要流程:读取data文件,解密,以流的形式返回给mybatis.
通过mybatis类就可以在程序的任意地方进行调用了。

除了使用xml方式配置mybatis外,还可以完全使用java代码进行配置,这种方式比较麻烦,需要创建一个datasource,然后用mybatis配置类加载所有需要的mapper.class,这里就不详细介绍了(除非有需要)。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网