OrmLite动态创建表,一个实体类创建多张表的的偏招
版权声明:本文为博主原创文章。未经博主同意不得转载。 https://blog.csdn.net/LonelyRoamer/article/details/26299355
在做一个Android的项目,由于使用数据库频繁,实体字段也比較多,于是打算採用ORM框架,发现OrmLite还不错,于是下了下来,打算使用。
没想到还没正式开工,就遇到问题了。我如今的一个需求例如以下,
我有一个实体类例如以下。代表聊天消息,如今要做的是针对每个当前用户(userId)相应一个朋友(friendId)都要创建一个表。
需求比較蛋疼,我本来想的是直接在加两个字段就搞定的。可是我们老大说要分表。没办法仅仅能分表。
public class ChatMessage{
public ChatMessage() {
}
private int _id;
private int type;
private String content;
/*get and set...*/
}
在OrmLite里面创建表和Dao的基本使用方法例如以下:
DatabaseTableConfig<ChatMessage> config = DatabaseTableConfigUtil.fromClass(mHelper.getConnectionSource(), ChatMessage.class);
TableUtils.createTableIfNotExists(mHelper.getConnectionSource(),config);
dao = DaoManager.createDao(mHelper.getConnectionSource(), config);
这样我们就拿到了Dao对象,就能够进行数据操作了。
可是这种方法的对我上面的需求并无论用,由于此方法拿到的数据库表名是固定的tableName="ChatMessage",我如今逍遥的表名肯定是不能固定的,他的格式是tableName="ChatMessage"+userId+friendId。即使在confi里面config.setTableName(tableName) 一样无论用。
查看了OrmLite的源代码,发如今DaoManager里面。依据相同的DatabaseTableConfig和类名做了缓存,于是每次拿到的Dao都是相同的Dao
TableConfigConnectionSource tableKey = new TableConfigConnectionSource(connectionSource, tableConfig);
// look up in the table map
Dao<?
, ?> dao = lookupDao(tableKey);
if (dao != null) {
@SuppressWarnings("unchecked")
D castDao = (D) dao;
return castDao;
}
// now look it up in the class map
Class<T> dataClass = tableConfig.getDataClass();
ClassConnectionSource classKey = new ClassConnectionSource(connectionSource, dataClass);
dao = lookupDao(classKey);
if (dao != null) {
// if it is not in the table map but is in the class map, add it
addDaoToTableMap(tableKey, dao);
@SuppressWarnings("unchecked")
D castDao = (D) dao;
return castDao;
}
相同的TableUtils.createTableIfNotExists一样进行了推断,使得你的相同的实体类不能创建多张表。
OrmLite这样做肯定是为了性能的优化和数据异步操作的安全性,可是这却妨碍了更加方便的使用了。于是研究下。略微使了点偏招,来达到我上面的需求。
1、首先建个类。例如以下:
import java.sql.SQLException;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;
import com.roamer.bean.ChatMessage;
public class ChatMessageDaoImpl extends BaseDaoImpl<ChatMessage, Integer>{
public ChatMessageDaoImpl(ConnectionSource connectionSource, DatabaseTableConfig<ChatMessage> tableConfig) throws SQLException {
super(connectionSource, tableConfig);
}
}
实现BaseDaoImpl的原因是,查看源代码,发如今DaoManager.createDao中实例化普通Modal,最后实际都是BaseDaoImpl类。
DatabaseTable databaseTable = tableConfig.getDataClass().getAnnotation(DatabaseTable.class);
if (databaseTable == null || databaseTable.daoClass() == Void.class
|| databaseTable.daoClass() == BaseDaoImpl.class) {
Dao<T, ?> daoTmp = BaseDaoImpl.createDao(connectionSource, tableConfig);
dao = daoTmp;
} else {
Class<?
> daoClass = databaseTable.daoClass();
Object[] arguments = new Object[] { connectionSource, tableConfig };
Constructor<?> constructor = findConstructor(daoClass, arguments);
if (constructor == null) {
throw new SQLException(
"Could not find public constructor with ConnectionSource, DatabaseTableConfig parameters in class "
+ daoClass);
}
try {
dao = (Dao<?
, ?>) constructor.newInstance(arguments);
} catch (Exception e) {
throw SqlExceptionUtil.create("Could not call the constructor in class " + daoClass, e);
}
}
2、ChatMessageDaoImpl指定daoClass
@DatabaseTable(daoClass=ChatMessageDaoImpl.class)
public class ChatMessage{
public ChatMessage() {
}
@DatabaseField(generatedId=true)
private int _id;
@DatabaseField
private int type;
@DatabaseField
private String content;
/*get and set*/
}
3、仿照DaoManager,实现一个不缓存的UnlimitDaoManager
package com.roamer.db;
import java.lang.reflect.Constructor;
import java.sql.SQLException;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.SqlExceptionUtil;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTable;
import com.j256.ormlite.table.DatabaseTableConfig;
public class UnlimitDaoManager {
public synchronized static <D extends Dao<T, ?>, T> D createDao(ConnectionSource connectionSource,
DatabaseTableConfig<T> tableConfig) throws SQLException {
if (connectionSource == null) {
throw new IllegalArgumentException("connectionSource argument cannot be null");
}
return doCreateDao(connectionSource, tableConfig);
}
private static Constructor<?> findConstructor(Class<?
> daoClass, Object[] params) {
for (Constructor<?
> constructor : daoClass.getConstructors()) {
Class<?>[] paramsTypes = constructor.getParameterTypes();
if (paramsTypes.length == params.length) {
boolean match = true;
for (int i = 0; i < paramsTypes.length; i++) {
if (!paramsTypes[i].isAssignableFrom(params[i].getClass())) {
match = false;
break;
}
}
if (match) {
return constructor;
}
}
}
return null;
}
private static <D extends Dao<T, ?>, T> D doCreateDao(ConnectionSource connectionSource,
DatabaseTableConfig<T> tableConfig) throws SQLException {
Dao<?, ?> dao = null;
// build the DAO using the table information
DatabaseTable databaseTable = tableConfig.getDataClass().getAnnotation(DatabaseTable.class);
if (databaseTable == null || databaseTable.daoClass() == Void.class
|| databaseTable.daoClass() == BaseDaoImpl.class) {
return null;
} else {
Class<?
> daoClass = databaseTable.daoClass();
Object[] arguments = new Object[] { connectionSource, tableConfig };
Constructor<?> constructor = findConstructor(daoClass, arguments);
if (constructor == null) {
throw new SQLException(
"Could not find public constructor with ConnectionSource, DatabaseTableConfig parameters in class "
+ daoClass);
}
try {
dao = (Dao<?
, ?>) constructor.newInstance(arguments);
} catch (Exception e) {
throw SqlExceptionUtil.create("Could not call the constructor in class " + daoClass, e);
}
}
@SuppressWarnings("unchecked")
D castDao = (D) dao;
return castDao;
}
}
4、由于上面没有使用DaoManager,所以为了性能和安全的考虑。我们还是要主要的实现下面缓存功能。下一个数据库操作的工具类,例如以下:
package com.roamer.dao;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.j256.ormlite.android.DatabaseTableConfigUtil;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.table.DatabaseTableConfig;
import com.roamer.bean.ChatMessage;
import com.roamer.db.SQLiteHelper;
import com.roamer.db.UnlimitDaoManager;
public class ChatMessageUtil {
private static ChatMessageUtil instance;
public static ChatMessageUtil getInstance(Context context) {
if (instance == null) {
instance = new ChatMessageUtil(context);
}
return instance;
}
private SQLiteHelper mHelper;
private static final String PREFIX = "message_prefix";
public ChatMessageUtil(Context context) {
mHelper = OpenHelperManager.getHelper(context, SQLiteHelper.class);
}
private Map<String, Dao<ChatMessage, Integer>> mDaoMap = new HashMap<String, Dao<ChatMessage, Integer>>();
private Dao<ChatMessage, Integer> getDao(String userId, String friendId) {
String tableName = PREFIX + userId + friendId;
if (mDaoMap.containsKey(tableName)) {
return mDaoMap.get(tableName);
}
Dao<ChatMessage, Integer> dao = null;
try {
DatabaseTableConfig<ChatMessage> config = DatabaseTableConfigUtil.fromClass(mHelper.getConnectionSource(), ChatMessage.class);
config.setTableName(tableName);
createTableIfNotExist(tableName);
dao = UnlimitDaoManager.createDao(mHelper.getConnectionSource(), config);
} catch (SQLException e) {
e.printStackTrace();
}
if (dao != null) {
mDaoMap.put(tableName, dao);
}
return dao;
}
private void createTableIfNotExist(String tableName) {
if (isTableExist(tableName)) {
return;
}
String sql = "CREATE TABLE " + tableName + " (content VARCHAR , _id INTEGER PRIMARY KEY AUTOINCREMENT , type INTEGER )";
mHelper.getWritableDatabase().execSQL(sql);
Log.d("roamer", "isTableExist(tableName):" + isTableExist(tableName));
}
private boolean isTableExist(String tableName) {
boolean result = false;
if (tableName == null) {
return false;
}
Cursor cursor = null;
try {
String sql = "select count(*) as c from Sqlite_master where type ='table' and name ='" + tableName.trim() + "' ";
cursor = mHelper.getReadableDatabase().rawQuery(sql, null);
if (cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
result = true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
public void addMessage(String userId, String friendId, ChatMessage message) {
Dao<ChatMessage, Integer> dao = getDao(userId, friendId);
try {
dao.create(message);
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<ChatMessage> getAllMessage(String userId, String friendId) {
Dao<ChatMessage, Integer> dao = getDao(userId, friendId);
try {
return dao.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
在这个里面,没有使用TableUtils来创建表。而是使用了原生SQL语句。
最后经測试。能够达到我拿蛋疼的需求。
写这个文章。是看到有人遇到和我相同的需求。不知道怎么解决,需求有点帮助。
OrmLite动态创建表,一个实体类创建多张表的的偏招的更多相关文章
- 使用Visual Studio 快速把 Json,Xml 字符串创建为一个实体类
- 通过myEclipse创建hibernate的实体类
今天有个新项目中需要使用到hibernate,刚好数据库表已经创建完毕,就顺便来总结一下通过myEclipse创建hibernate的实体类. 1..在myEclipse中选择MyEclipse Da ...
- C# Emit动态代理生成一个实体对象
/// <summary> /// 使用Emit动态代理收集实体信息 /// </summary> /// <typeparam name="T"&g ...
- Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作
Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作 1>. 创建一个控制台程序2>. 添加一个 ADO.NET实体数据模型,选择对应的数据库与表(Studen ...
- 如何通过java反射将数据库表生成实体类?
首先有几点声明: 1.代码是在别人的基础进行改写的: 2.大家有什么改进的意见可以告诉我,也可以自己改好共享给其他人: 3.刚刚毕业,水平有限,肯定有许多不足之处: 4.希望刚刚学习java的同学能有 ...
- sql把一个表数据插入到另一张表
把一个表数据插入到另一张表 insert into tableB (field1,field2,field3,field4) select field1,field2,field3,'val4' fr ...
- hibernate多表查询,结果封装在自己定义的一个实体类当中(在自己定义的类中增加构造函数)
hibernate的hql查询直接返回java对象时出现问题3 向大家请教一个问题,现在有三张表,表之间没有关联,我需要将三张表里面的所有东西查询出来存储到一个新的对象中,该如何实现,使用hibern ...
- [04] 利用注解生成实体类对应的建表sql语句
1.实现功能 我们已经对注解有了基本的认识,知道了如何自定义注解,如何使用和最基本的处理注解. 本篇主要介绍,如何使用运行时级别的注解,配合反射来自动生成建表的sql语句.如下例: 我们有实体类Stu ...
- 阶段3 1.Mybatis_12.Mybatis注解开发_5 mybatis注解建立实体类属性和数据库表中列的对应关系
创建新项目,一对多 复制刚才关闭的项目的文件 复制到们的新项目里面 复制包的依赖 删减相关代码.只保留这三个查询的方法 模糊查询改成传统的占位符的方式 之前是可以自定义实体类的属性字段,和数据库的字典 ...
随机推荐
- Android ActionBar自定义
关于自定义的ActionBar的实现过程,这里做下笔记以供之后查看. 1.默认状态 使用Android Studio新建一个名为“ActionBar”的应用,默认actionbar如图(1)所示. 图 ...
- python webdriver 报错WebDriverException: Message: can't access dead object的原因(pycharm中)
PyCharm中运行firefox webdriver访问邮箱添加通讯录的时候报错-WebDriverException: Message: can't access dead object 调了半天 ...
- luogu P1162 填涂颜色
https://www.luogu.org/problem/show?pid=1162 //其实很简单的吧 //就是最外圈加一圈0 ,然后把外圈里面的0都遍历了 //剩下的0 就变成2 就行了 #in ...
- POJ 1047 Round and Round We Go
https://vjudge.net/problem/POJ-1047 题意: 给一个整数,它的长度为n,从1开始一直到n和该整数相乘,判断每次结果是否和原来的整数是循环的. 思路: 大整数的乘法. ...
- VuePress从零开始搭建自己的博客
VuePress是什么? VuePress是以Vue驱动的静态网站生成器,是一个由Vue.Vue Router和webpack驱动的单页应用.在VuePress中,你可以使用Markdown编写文档, ...
- Decorator(装饰)
意图: 动态地给一个对象添加一些额外的职责.就增加功能来说,Decorator 模式相比生成子类更为灵活. 适用性: 在不影响其他对象的情况下,以动态.透明的方式给单个对象添加职责. 处理那些可以撤消 ...
- JavaScript--语法2--语句结构
JavaScript--语句结构 一.心得 判断的时候常量放左边java中switch只支持四种类型,javaScript是弱类型,所有的都支持. 显示方法: 77 // alert("x= ...
- hdu1846巴什博弈
巴什博弈:只有一堆n个物品,两个人轮流从这堆物品中取物, 规定每次至少取一个,最多取m个.最后取光者得胜. 结论:只要不能整除,那么必然是先手取胜,否则后手取胜. #include<map> ...
- HDU 4522 (恶心建图)
湫湫系列故事——过年回家 Time Limit: 500/200 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total ...
- 在请求的参数中设置可选值列表为当前职责可访问的所有OU
方法一: 实现此需求的前提之一是为该请求开启多业务实体访问,开启方法 系统管理员->系统管理->并发->程序,进入OAF页面,查询你的并发,然后点更新,选择请求,在业务实体模式下选择 ...