Android - OrmLite 实现仿Web那样写Dao
本文转自OSCHINA
写了一个demo,这个实例,只针对单一的实体bean,日后在补充其他示例
实体bean
BaseColumn.java
package org.mo.ormlite.entity; import com.j256.ormlite.field.DatabaseField; import java.io.Serializable; /** * Created by moziqi on 2015/1/18 0018. */ public abstract class BaseColumn implements Serializable { @DatabaseField(generatedId = true, columnName = "_id") private Long id; @DatabaseField(columnName = "create_date") private String createDate; @DatabaseField(columnName = "update_date") private String updateDate; //getset自己补充 }
User.java
package org.mo.ormlite.entity; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; import java.util.List; /** * Created by moziqi on 2015/1/18 0018. */ @DatabaseTable(tableName = "tb_user") public class User extends BaseColumn { @DatabaseField(index = true, columnName = "username") private String username; @DatabaseField(canBeNull = false, columnName = "password") private String password; @DatabaseField(columnName = "login_time") private String loginTime; //getset自己补充 @Override public String toString() { final StringBuffer sb = new StringBuffer("User{"); sb.append("username='").append(username).append('\''); sb.append(", password='").append(password).append('\''); sb.append(", loginTime='").append(loginTime).append('\''); sb.append('}'); return sb.toString(); } }
Dao操作
DatabaseHelper.java
package org.mo.ormlite.dao; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import org.mo.ormlite.entity.User; import org.mo.util.MyConstant; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; /** * Created by moziqi on 2015/1/18 0018. */ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private final static String TAG = DatabaseHelper.class.getSimpleName(); private Dao<User, Long> userDao = null; private Map<String, Dao> daos = new HashMap<String, Dao>(); private static DatabaseHelper instance; public DatabaseHelper(Context context) { super(context, MyConstant.MyDB.DATABASE_NAME, null, MyConstant.MyDB.DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, User.class); } catch (SQLException e) { Log.e(TAG, e.getMessage()); } } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) { try { TableUtils.dropTable(connectionSource, User.class, true); onCreate(sqLiteDatabase, connectionSource); } catch (SQLException e) { Log.e(TAG, e.getMessage()); } } public Dao<User, Long> getUserDao() throws SQLException { if (userDao == null) { userDao = getDao(User.class); } return userDao; } /** * 单例获取该Helper * * @param context * @return */ public static synchronized DatabaseHelper getHelper(Context context) { context = context.getApplicationContext(); if (instance == null) { synchronized (DatabaseHelper.class) { if (instance == null) instance = new DatabaseHelper(context); } } return instance; } public synchronized Dao getDao(Class clazz) throws SQLException { Dao dao = null; String className = clazz.getSimpleName(); if (daos.containsKey(className)) { dao = daos.get(className); } if (dao == null) { dao = super.getDao(clazz); daos.put(className, dao); } return dao; } /** * 释放资源 */ @Override public void close() { super.close(); for (String key : daos.keySet()) { Dao dao = daos.get(key); dao = null; } } }
UserDao.java
package org.mo.ormlite.dao; import android.content.Context; import com.j256.ormlite.dao.Dao; import org.mo.ormlite.entity.User; import java.sql.SQLException; import java.util.List; /** * Created by moziqi on 2015/1/18 0018. */ public class UserDao implements BaseDao<User> { private Context mContext; private Dao<User, Long> mUserLongDao; private DatabaseHelper mDatabaseHelper; public UserDao(Context mContext) { this.mContext = mContext; try { this.mDatabaseHelper = DatabaseHelper.getHelper(mContext); this.mUserLongDao = mDatabaseHelper.getDao(User.class); } catch (SQLException e) { e.printStackTrace(); } } /** * 不存在,返回false * * @param username * @return */ public boolean findByUsername(String username) { boolean flag = false; try { List<User> users = mUserLongDao.queryForEq("username", username); if (users.size() > 0) { flag = true; } } catch (SQLException e) { e.printStackTrace(); } return flag; } @Override public boolean save(final User entity) { boolean flag = false; try { int result = mUserLongDao.create(entity); if (result > 0) { flag = true; } } catch (SQLException e) { e.printStackTrace(); } return flag; } @Override public boolean update(final User entity) { boolean flag = false; try { int result = mUserLongDao.update(entity); if (result > 0) { flag = true; } } catch (SQLException e) { e.printStackTrace(); } return flag; } @Override public boolean delete(final User entity) { boolean flag = false; try { int result = mUserLongDao.delete(entity); if (result > 0) { flag = true; } } catch (SQLException e) { e.printStackTrace(); } return flag; } @Override public List<User> findAll() { List<User> users = null; try { users = mUserLongDao.queryForAll(); } catch (SQLException e) { e.printStackTrace(); } return users; } @Override public User findOneById(final long id) { User user = null; try { user = mUserLongDao.queryForId(id); } catch (SQLException e) { e.printStackTrace(); } return user; } @Override public long countAll() { long count = 0; try { count = mUserLongDao.countOf(); } catch (SQLException e) { e.printStackTrace(); } return count; } /** * 拼接查询,分页查询 * * @param offset * @param limit * @return */ @Override public List<User> findAllByLimit(final long offset, final long limit) { List<User> query = null; try { query = mUserLongDao.queryBuilder(). orderBy("create_date", false). offset(offset). limit(limit). query(); } catch (SQLException e) { e.printStackTrace(); } return query; } }
service层
UserService.java
package org.mo.ormlite.service; import android.content.Context; import android.widget.Toast; import com.j256.ormlite.android.AndroidDatabaseConnection; import com.j256.ormlite.support.DatabaseConnection; import org.mo.ormlite.R; import org.mo.ormlite.dao.DatabaseHelper; import org.mo.ormlite.dao.UserDao; import org.mo.ormlite.entity.User; import java.sql.SQLException; import java.sql.Savepoint; import java.util.List; /** * Created by moziqi on 2015/1/18 0018. */ public class UserService { // 添加事物 public DatabaseConnection connection; private UserDao mUserDao; private Context mContext; public UserService(Context mContext) { this.mContext = mContext; mUserDao = new UserDao(mContext); connection = new AndroidDatabaseConnection( DatabaseHelper.getHelper(mContext).getWritableDatabase(), true); } /** * 参考这个,其他加事务吧 * * @param user * @return */ public int saveUser(User user) { int flag = -1;//保存失败 Savepoint savepoint = null; try { boolean byUsername = mUserDao.findByUsername(user.getUsername()); if (byUsername) { flag = 0;//用户名存在 } else { savepoint = connection.setSavePoint("save"); if (mUserDao.save(user)) { flag = 1;//保存成功 connection.commit(savepoint); } } } catch (SQLException e) { try { e.printStackTrace(); connection.rollback(savepoint); } catch (SQLException e1) { e1.printStackTrace(); } } return flag; } public boolean updateUser(User user) { return mUserDao.update(user); } public boolean deleteUser(User user) { return mUserDao.delete(user); } public User getUserById(long id) { return mUserDao.findOneById(id); } public List<User> getAll() { List<User> users = mUserDao.findAll(); return users; } public long countAll() { return mUserDao.countAll(); } public List<User> getAllByLimit(long currentPage, long size) { return mUserDao.findAllByLimit(currentPage - 1, size); } }
------------------------------
Brant Liu
lbf1988@qq.com
有梦想的码农
Brant Liu
lbf1988@qq.com
有梦想的码农