Ormlite Android如何找到插入或更新

时间:2014-07-16 06:21:45

标签: android ormlite foreign-collection

我在我的Android应用程序中使用了Ormlite数据库,并使用GSon库进行服务数据解析。我遇到问题第一次与服务器同步时我有一个类似于Ground的模型,存储在DB中的模型和服务器端的id字段是重复的在模型中,如同相同的id,但模型中的两个对象,当我将这些模型传递给DB(ORMLIte)然后插入一行,当第二次再次与服务器同步然后再次进行相同的过程但是当添加到Db时,异常彻底的主键必须是unique,我的问题是我怎么才能发现模型中的这个对象已经存在于DB中,现在查询更新或插入。

玩家模型

package com.tt.models;
import java.util.Collection;
import com.google.gson.annotations.SerializedName;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "Player")
public class Player {
    public static final String BATTING_ID_FIELD_NAME = "batting_id";
    public static final String BOWLING_ID_FIELD_NAME = "bowling_id";
    public static final String TEAM_ID_FIELD_NAME = "team_id";
    @SerializedName("__v")
    @DatabaseField(id = true) 
     private int id;
    @SerializedName("_id")
    @DatabaseField(columnName = "_id")
    private String _id;
    /*@SerializedName("__v")
    @DatabaseField(columnName = "__v",id=true)
    private int __v;*/
    @DatabaseField
    private String battingStyle;
    @DatabaseField
    private String bowlingStyle;
    @DatabaseField
    private String dob;
    @DatabaseField
    private String playingRole;
    @DatabaseField
    private String sname;
    @DatabaseField
    private String fname;
    @SerializedName("gallery")
    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    private Collection<Gallery> gallery;

    @SerializedName("games")
    @ForeignCollectionField(eager = true)
    private Collection<Game> games;

    /*
     * @DatabaseField(dataType = DataType.SERIALIZABLE) private String[] users;
     */
    /*
     * @DatabaseField(dataType = DataType.SERIALIZABLE) private String[] squad;
     */

    Player() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    public String getBattingStyle() {
        return battingStyle;
    }

    public void setBattingStyle(String battingStyle) {
        this.battingStyle = battingStyle;
    }

    public String getBowlingStyle() {
        return bowlingStyle;
    }

    public void setBowlingStyle(String bowlingStyle) {
        this.bowlingStyle = bowlingStyle;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getPlayingRole() {
        return playingRole;
    }

    public void setPlayingRole(String playingRole) {
        this.playingRole = playingRole;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    /*
     * public String[] getUsers() { return users; }
     * 
     * public void setUsers(String[] users) { this.users = users; }
     */

    /*
     * public String[] getSquad() { return squad; }
     * 
     * public void setSquad(String[] squad) { this.squad = squad; }
     */

    public Collection<Gallery> getGallerys() {
        return gallery;
    }

    public void setGallerys(Collection<Gallery> gallery) {
        this.gallery = gallery;
    }

    public Collection<Gallery> getGallery() {
        return gallery;
    }

    public void setGallery(Collection<Gallery> gallery) {
        this.gallery = gallery;
    }

    public Collection<Game> getGames() {
        return games;
    }

    public void setGames(Collection<Game> games) {
        this.games = games;
    }

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    @Override
    public String toString() {
        return "Player [id=" + id + ", _id=" + _id + ", battingStyle="
                + battingStyle + ", bowlingStyle=" + bowlingStyle + ", dob="
                + dob + ", playingRole=" + playingRole + ", sname=" + sname
                + ", fname=" + fname + ", gallery=" + gallery + ", games="
                + games + "]";
    }


}

游戏模型

package com.tt.models;

import java.util.Collection;

import com.google.gson.annotations.SerializedName;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "Game")
public class Game {
    public static final String INNING_ID_FIELD_NAME = "inning_id";
    public static final String PLAYER_ID_FIELD_NAME = "player_id";
    @SerializedName("__v")
    @DatabaseField(id = true)
    private int id;

    /*
     * @SerializedName("_id")
     * 
     * @DatabaseField(columnName = "_id") private String _id;
     * 
     * @SerializedName("__v")
     * 
     * @DatabaseField(columnName = "__v",id=true) private int __v;
     */
    @SerializedName("gameType")
    @DatabaseField
    private String gameType;
    @SerializedName("name")
    @DatabaseField
    private String name;
    @SerializedName("totalOvers")
    @DatabaseField
    private String totalOvers;
    @SerializedName("dateStarted")
    @DatabaseField
    private String dateStarted;
    @SerializedName("dateEnded")
    @DatabaseField
    private String dateEnded;
    @SerializedName("innings")
    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    private Collection<Inning> innings;
    @DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, columnName = PLAYER_ID_FIELD_NAME)
    private transient Player player;
    @SerializedName("grounds")
    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    private Collection<Ground> grounds;
    @SerializedName("teams")
    @ForeignCollectionField(eager = true, maxEagerLevel = 2)
    private Collection<Team> teams;

    public Game() {
        // all persisted classes must define a no-arg constructor with at least
        // package visibility
    }

    /*
     * public String get_id() { return _id; }
     * 
     * public void set_id(String _id) { this._id = _id; }
     */

    public String getGameType() {
        return gameType;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setGameType(String gameType) {
        this.gameType = gameType;
    }

    public Collection<Ground> getGrounds() {
        return grounds;
    }

    public void setGrounds(Collection<Ground> grounds) {
        this.grounds = grounds;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDateStarted() {
        return dateStarted;
    }

    public void setDateStarted(String dateStarted) {
        this.dateStarted = dateStarted;
    }

    public String getDateEnded() {
        return dateEnded;
    }

    public void setDateEnded(String dateEnded) {
        this.dateEnded = dateEnded;
    }

    public String getTotalOvers() {
        return totalOvers;
    }

    public void setTotalOvers(String totalOvers) {
        this.totalOvers = totalOvers;
    }

    public Player getPlayer() {
        return player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public Collection<Inning> getInnings() {
        return innings;
    }

    public void setInnings(Collection<Inning> innings) {
        this.innings = innings;
    }

    public Collection<Team> getTeams() {
        return teams;
    }

    public void setTeams(Collection<Team> teams) {
        this.teams = teams;
    }

    @Override
    public String toString() {
        return "Game [id=" + id + ", gameType=" + gameType + ", name=" + name
                + ", totalOvers=" + totalOvers + ", dateStarted=" + dateStarted
                + ", dateEnded=" + dateEnded + ", innings=" + innings
                + ", grounds=" + grounds + ", teams=" + teams + "]";
    }

}

地面模型

package com.tt.models;

import android.widget.Toast;

import com.google.gson.annotations.SerializedName;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import com.tt.Utilities.Utils;

@DatabaseTable(tableName = "Ground")
public class Ground {
    public static final String GAME_ID_FIELD_NAME = "game_id";

    @SerializedName("__v")
    @DatabaseField(id = true)
    private int id;

    /*
     * @SerializedName("_id")
     * 
     * @DatabaseField(columnName = "_id",unique=true) private String _id;
     * 
     * @SerializedName("__v")
     * 
     * @DatabaseField(columnName = "__v",id=true) private int __v;
     */
    @SerializedName("address")
    @DatabaseField
    private String address;
    @SerializedName("city")
    @DatabaseField
    private String city;
    @SerializedName("country")
    @DatabaseField
    private String country;
    @SerializedName("name")
    @DatabaseField
    private String name;
    @DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, maxForeignAutoRefreshLevel = 3, columnName = GAME_ID_FIELD_NAME)
    private transient Game game;

    public Ground() {
        // all persisted classes must define a no-arg constructor with at least
        // package visibility
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getGameType() {
        return address;
    }

    public void setGameType(String gameType) {
        this.address = gameType;
    }

    public Game getGame() {
        return game;
    }

    public void setGame(Game game) {
        this.game = game;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Ground [id=" + id + ", address=" + address + ", city=" + city
                + ", country=" + country + ", name=" + name + "]";
    }

}

播放器控制器

package com.tt.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Environment;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.ForeignCollection;
import com.tt.Utilities.Utils;
import com.tt.database.Database;
import com.tt.models.Batting;
import com.tt.models.Bowling;
import com.tt.models.Fielding;
import com.tt.models.Gallery;
import com.tt.models.Game;
import com.tt.models.Ground;
import com.tt.models.Inning;
import com.tt.models.Player;
import com.tt.models.Team;

public class PlayerController {

    private static PlayerController instance;

    private PlayerController() {

    }

    public List<Player> getPlayers() throws SQLException {
        // query for all of the data objects in the database
        return Database.getSingletonInstance(Utils.context).getPlayerDao()
                .queryForAll();
    }

    public static PlayerController getSingletonInstance() {
        if (instance == null) {
            instance = new PlayerController();
        }
        return instance;
    }

    public Player JsonParse(JSONObject jsonObject) {
        Player player = null;
        try {

            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();

            player = gson.fromJson(jsonObject.getString("players")
                    , Player.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return player;
    }

    @SuppressWarnings("unused")
    private void writeToSdcard(Player response) {
        try {
            File newFolder = new File(
                    Environment.getExternalStorageDirectory(), "TestFolder");
            if (!newFolder.exists()) {
                newFolder.mkdir();
            }
            try {
                File file = new File(newFolder, "PlayerModel" + ".txt");
                file.createNewFile();
                FileOutputStream fOut = new FileOutputStream(file);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                myOutWriter.append(response.toString());
                myOutWriter.close();
                fOut.close();
            } catch (Exception ex) {
                System.out.println("ex: " + ex);
            }
        } catch (Exception e) {
            System.out.println("e: " + e);
        }
    }

    public int savePlayerDB(Player player) {
        int Count = 0;
   writeToSdcard(player);
        try {

            ForeignCollection<Batting> battings = Database
                    .getSingletonInstance(Utils.context).getInningDao()
                    .getEmptyForeignCollection("battings");
            ForeignCollection<Bowling> bowlings = Database
                    .getSingletonInstance(Utils.context).getInningDao()
                    .getEmptyForeignCollection("bowlings");
            ForeignCollection<Fielding> fieldings = Database
                    .getSingletonInstance(Utils.context).getInningDao()
                    .getEmptyForeignCollection("Fieldings");
            ForeignCollection<Team> teams = Database
                    .getSingletonInstance(Utils.context).getGameDao()
                    .getEmptyForeignCollection("teams");
            ForeignCollection<Gallery> gallery = Database
                    .getSingletonInstance(Utils.context).getPlayerDao()
                    .getEmptyForeignCollection("gallery");
            /*
             * ForeignCollection<Inning> innings = Database
             * .getSingletonInstance(Utils.context).getBattingDao()
             * .getEmptyForeignCollection("innings");
             */
            /*
             * ForeignCollection<Game> games = Database
             * .getSingletonInstance(Utils.context).getInningDao()
             * .getEmptyForeignCollection("games");
             */


            ForeignCollection<Ground> grounds = Database
                    .getSingletonInstance(Utils.context).getGameDao()
                    .getEmptyForeignCollection("grounds");
            Iterator<Game> iteratorGame = player.getGames().iterator();
            while (iteratorGame.hasNext()) {
                Game game = (Game) iteratorGame.next();
                if (game != null) {
                    game.setPlayer(player);

                    Iterator<Inning> iteratorInning = game.getInnings()
                            .iterator();
                    while (iteratorInning.hasNext()) {
                        Inning inning = (Inning) iteratorInning.next();
                        if (inning != null) {
                            inning.setGame(game);
                            if (inning.getBattings() != null) {
                                Iterator<Batting> iteratorBattings = inning
                                        .getBattings().iterator();

                                while (iteratorBattings.hasNext()) {
                                    Batting batting = (Batting) iteratorBattings
                                            .next();
                                    if (batting != null) {
                                        if (batting.getPlayer()[0]
                                                .equalsIgnoreCase(player
                                                        .get_id()))
                                            batting.setInning(inning);
                                    }
                                }

                                battings.addAll(inning.getBattings());
                            }
                            if (inning.getBowlings() != null) {
                                Iterator<Bowling> iteratorBowlings = inning
                                        .getBowlings().iterator();
                                while (iteratorBowlings.hasNext()) {
                                    Bowling bowling = (Bowling) iteratorBowlings
                                            .next();
                                    if (bowling != null) {
                                        if (bowling.getPlayer()[0]
                                                .equalsIgnoreCase(player
                                                        .get_id()))
                                            bowling.setInning(inning);
                                    }
                                }
                                bowlings.addAll(inning.getBowlings());
                            }
                            if (inning.getFieldings() != null) {
                                Iterator<Fielding> iteratorFieldings = inning
                                        .getFieldings().iterator();

                                while (iteratorFieldings.hasNext()) {
                                    Fielding fielding = (Fielding) iteratorFieldings
                                            .next();
                                    if (fielding != null) {
                                        if (fielding.getPlayer()[0]
                                                .equalsIgnoreCase(player
                                                        .get_id()))
                                            fielding.setInning(inning);
                                    }
                                }
                                fieldings.addAll(inning.getFieldings());
                            }
                        }
                    }
                    // innings.addAll(batting.getInnings());
                    Iterator<Ground> iteratorGround = game.getGrounds()
                            .iterator();
                    while (iteratorGround.hasNext()) {
                        Ground ground = (Ground) iteratorGround.next();
                        if (ground != null) {
                            ground.setGame(game);

                        }
                    }

                    grounds.addAll(game.getGrounds());
                    Iterator<Team> iteratorTeam = game.getTeams().iterator();
                    while (iteratorTeam.hasNext()) {
                        Team team = (Team) iteratorTeam.next();
                        if (team != null) {
                            team.setGame(game);

                        }
                    }
                    teams.addAll(game.getTeams());


                }

            }
            /*
             * Iterator<Bowling> iteratorBowling =
             * player.getBowlings().iterator(); while
             * (iteratorBowling.hasNext()) { Bowling bowling = (Bowling)
             * iteratorBowling.next(); bowling.setPlayer(player);
             * Iterator<Inning> iteratorInning =
             * bowling.getInnings().iterator(); while (iteratorInning.hasNext())
             * { Inning inning = (Inning) iteratorInning.next();
             * if(inning!=null){ inning.setBowling(bowling); Iterator<Game>
             * iteratorGame = inning.getGames().iterator(); while
             * (iteratorGame.hasNext()) { Game game = (Game)
             * iteratorGame.next(); if(game!=null) { game.setInning(inning);
             * Iterator<Ground> iteratorGround = game.getGrounds().iterator();
             * while (iteratorGround.hasNext()) { Ground ground = (Ground)
             * iteratorGround.next(); if(ground!=null) { ground.setGame(game);
             * grounds.addAll(game.getGrounds()); } } } }
             * //innings.addAll(batting.getInnings()); } } }
             */

            /*
             * Iterator<Team> iteratorTeam = player.getTeams().iterator(); while
             * (iteratorTeam.hasNext()) { Team team = (Team)
             * iteratorTeam.next(); team.setPlayer(player); }
             */
            Iterator<Gallery> iteratorGallery = player.getGallerys().iterator();
            while (iteratorGallery.hasNext()) {
                Gallery galleryobj = (Gallery) iteratorGallery.next();
                galleryobj.setPlayer(player);
            }
            // battings.addAll(player.getBattings());
            // bowlings.addAll(player.getBowlings());
            // teams.addAll(player.getTeams());
            gallery.addAll(player.getGallerys());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Count;
    }
}
使用Gson google lib解析json之后的

播放器模型

Player[
  id=1,
  _id=531029b207987409620000d6,
  battingStyle=RHB,
  bowlingStyle=RAOS,
  dob=2000-02-28T06: 15: 15.264Z,
  playingRole=BWL,
  sname=QadeerButt,
  fname=Tahir,
  gallery=[

  ],
  games=[
    Game[
      id=4,
      gameType=T20‎,
      name=TotallyCricketvsLahoreTiger,
      totalOvers=20,
      dateStarted=2014-06-18T19: 00: 00.000Z,
      dateEnded=2014-06-18T19: 00: 00.000Z,
      innings=[

      ],
      grounds=[
        Ground[
          id=26,
          address=14835SE18thPl,
          Bellevue,
          WA98007,
          UnitedStates,
          city=Bellevue,
          country=UnitedStates,
          name=RobinswoodPark
        ],
        Ground[
          id=26,
          address=14835SE18thPl,
          Bellevue,
          WA98007,
          UnitedStates,
          city=Bellevue,
          country=UnitedStates,
          name=RobinswoodPark
        ]
      ],
      teams=[
        Team[
          id=30,
          name=TotallyCricket,
          category=Veterans,
          teamGender=Men,
          rating=5
        ],
        Team[
          id=19,
          name=LahoreTiger,
          category=Under19,
          teamGender=Men,
          rating=3
        ]
      ]
    ]
  ]
]

GSon From server

{
  "status": 1,
  "players": {
    "__v": 1,
    "_id": "531029b207987409620000d6",
    "battingStyle": "RHB",
    "bowlingStyle": "RAOS",
    "dob": "2000-02-28T06:15:15.264Z",
    "fname": "Tahir",
    "playingRole": "BWL",
    "sname": "Qadeer Butt",

        "teams": [
          {
            "__v": 30,
            "_id": "52f86b1d31f3b9b205000a58",
            "category": "Veterans",
            "name": "Totally Cricket",
            "rating": 5,
            "teamGender": "Men"
          },
          {
            "__v": 19,
            "_id": "52f9e64231f3b9b205000f36",
            "category": "Under19",
            "name": "Lahore Tiger",
            "rating": 3,
            "teamGender": "Men"
          }
        ],

        "grounds": [
          {
            "__v": 26,
            "_id": "53381c1bf0bce0bd20000002",
            "address": "14835 SE 18th Pl, Bellevue, WA 98007, United States",
            "city": "Bellevue",
            "country": "United States",
            "latitude": "",
            "longitude": "",
            "name": "Robinswood Park"
          },
          {
            "__v": 26,
            "_id": "53381c1bf0bce0bd20000002",
            "address": "14835 SE 18th Pl, Bellevue, WA 98007, United States",
            "city": "Bellevue",
            "country": "United States",
            "latitude": "",
            "longitude": "",
            "name": "Robinswood Park"
          }
        ]

  }
}***

0 个答案:

没有答案