@DatabaseTable(tableName = "goals") public class Goal{ public final static String GOAL_NAME_FIELD_NAME = "name"; @DatabaseField(generatedId = true) private int Id; @DatabaseField(canBeNull = false, dataType = DataType.STRING, columnName = GOAL_NAME_FIELD_NAME) private String name; @DatabaseField(dataType = DataType.DATE) private Date lastEditDate; @DatabaseField() private String notes; public Goal(){ scheduleList = new ArrayList<Shedule>(); priorities = new ArrayList<PrioritySchedule>(); } }
@DatabaseTable(tableName = "goals")
indicates the name of the table where objects of this class will be mapped.@DatabaseField
with different arguments. (you can also leave no arguments - everything will be set by default, and the name of the column in the table will be the same as the name of the field). The name field has three arguments. canBeNull = false
means that this column cannot be empty in a table. dataType = DataType.STRING
column type to a String
type. (available types can be found here ). columnName = GOAL_NAME_FIELD_NAME
- enforcing the name of a column in a table will help us later when building select queries to retrieve data from the database.id = true
, but it is recommended to make the auto- generatedId = true
id value and set it to generatedId = true
. ORMLite will assign it a unique number.index = true
specified index = true
public class HelperFactory{ private static DatabaseHelper databaseHelper; public static DatabaseHelper getHelper(){ return databaseHelper; } public static void setHelper(Context context){ databaseHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class); } public static void releaseHelper(){ OpenHelperManager.releaseHelper(); databaseHelper = null; } }
public class MyApplication extends Application{ @Override public void onCreate() { super.onCreate(); HelperFactory.setHelper(getApplicationContext()); } @Override public void onTerminate() { HelperFactory.releaseHelper(); super.onTerminate(); } }
<application android:name=".MyApplication" android:icon="@drawable/ic_launcher" android:label="@string/app_name" >
public class DatabaseHelper extends OrmLiteSqliteOpenHelper{ private static final String TAG = DatabaseHelper.class.getSimpleName(); // /data/data/APPNAME/DATABASE_NAME.db private static final String DATABASE_NAME ="myappname.db"; // , onUpgrade(); private static final int DATABASE_VERSION = 1; // DAO , private GoalDAO goalDao = null; private RoleDAO roleDao = null; public DatabaseHelper(Context context){ super(context,DATABASE_NAME, null, DATABASE_VERSION); } //, @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource){ try { TableUtils.createTable(connectionSource, Goal.class); TableUtils.createTable(connectionSource, Role.class); } catch (SQLException e){ Log.e(TAG, "error creating DB " + DATABASE_NAME); throw new RuntimeException(e); } } //, @Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVer, int newVer){ try{ // , TableUtils.dropTable(connectionSource, Goal.class, true); TableUtils.dropTable(connectionSource, Role.class, true); onCreate(db, connectionSource); } catch (SQLException e){ Log.e(TAG,"error upgrading db "+DATABASE_NAME+"from ver "+oldVer); throw new RuntimeException(e); } } // GoalDAO public GoalDAO getGoalDAO() throws SQLException{ if(goalDao == null){ goalDao = new GoalDAO(getConnectionSource(), Goal.class); } return goalDao; } / RoleDAO public RoleDAO getRoleDAO() throws SQLException{ if(roleDao == null){ roleDao = new RoleDAO(getConnectionSource(), Role.class); } return roleDao; } // @Override public void close(){ super.close(); goalDao = null; roleDao = null; } }
public class RoleDAO extends BaseDaoImpl<Role, Integer>{ protected RoleDAO(ConnectionSource connectionSource, Class<Role> dataClass) throws SQLException{ super(connectionSource, dataClass); } public List<Role> getAllRoles() throws SQLException{ return this.queryForAll(); } }
RoleDAO roleDao = HelperFactory.GetHelper().getRoleDAO();
public List<Goal> getGoalByName(String name) throws SQLException{ QueryBuilder<Goal, String> queryBuilder = queryBuilder(); queryBuilder.where().eq(Goal.GOAL_NAME_FIELD_NAME, "First goal"); PreparedQuery<Goal> preparedQuery = queryBuilder.prepare(); List<Goal> goalList =query(preparedQuery); return goalList; }
eq
(which means equals) there are others like gt
(greater), ge
(greater and equals) and the rest corresponding to the standard where-clauses in SQL (see the full list here )and
:queryBuilder.where().eq(Goal.GOAL_NAME_FIELD_NAME, "First goal").and().eq(Goal.GOAL_NOTES_NAME_FIELD_NAME,”aaa”);
@DatabaseField(foreign = true) private Role role; public void setRole(Role value){ this.role = value; } public Role getRole(){ return role; }
Goal g = new Goal(); g.setName(“asd”); Role r = new Role(); g.setRole(r); HelperFactory.getHelper.getRoleDAO().create(r); HelperFactory.getHelper.getGoalDAO().create(g);
Goal g = HelperFactory.getHelper.getRoleDAO().getGoalByName(“asd”); Role r = g.getRole(); HelperFactory.getHelper.getRolelDAO().refresh(g);
refresh()
must be performed so that r gets all the fields from the database corresponding to this object. @ForeignCollectionField(eager = true) private Collection<Role> roleList; public addRole(Role value){ value.setGoal(this); HelperFactory.GetHelper().getRoleDAO().create(value); roleList.add(value); } public void removeRole(Role value){ roleList.remove(value); HelperFactory.GetHelper().getRoleDAO().delete(value); }
eager
annotation means that all the objects from the roleList will be obtained from the database along with the retrieval of a Goal object. A reference to Goal in the Role object is required. And you also need to separately save each of the Role objects using RoleDAO. @DatabaseField(foreign = true, foreignAutoRefresh = true) private Goal goal;
eager=true
, then lazy-initialization will be performed, i.e. when the Goal object is requested, the objects of the corresponding roleList collection will not be retrieved. To extract them, you will need to iterate them: Iterator<Role> iter = state.goal.getRoleList().iterator(); while (iter.hasNext()) { Role r = iter.next(); }
Source: https://habr.com/ru/post/143431/
All Articles