根据侧重点的不同可以分为两类:
一是侧重子表,即CRUD操作主要是针对子表进行的,例如书中所举的例子album 是子表, artist是主表。
class AlbumMapper...
--1.Mapper实现的对象初始化
public Album find(Long id)
{ return (Album) abstractFind(d);
}
protected String findStatement()
{ return "SELECT ID, title, artistID FROM albums WHERE ID = ?"; }
--2.Mapper实现的更新过程
public void update(DomainObject arg) {
PreparedStatement statement = null;
try {
statement = DB.prepare(
"UPDATE albums SET title = ?, artistID = ? WHERE id = ?");
statement.setLong(3, arg.getID().longValue());
Album album = (Album) arg;
statement.setString(1, album.getTitle());
statement.setLong(2, album.getArtist().getID().longValue());
statement.execute();
} catch (SQLException e) {
throw new ApplicationException(e);
} finally {
cleanUp(statement);
}
二是侧重主表,例如Team与Player的关系。CRUD操作主要是针对主表进行的。子表所表示的对象以集合类的形式作为主对象的属性出现。
class TeamMapper...
protected override void doLoad (DomainObject obj, DataRow row) {
Team team = (Team) obj;
team.Name = (String) row["name"];
team.Players = MapperRegistry.Player.FindForTeam(team.Id);
}
protected override void Save (DomainObject obj, DataRow row)
{
Team team = (Team) obj;
row["name"] = team.Name;
savePlayers(team);
}
private void savePlayers(Team team){
foreach (Player p in team.Players) {
MapperRegistry.Player.LinkTeam(p, team.Id);
}
}
三看看各自的类设计就能明白侧重的意思3.1侧重子表的类设计是在子对象中有一个指向父类的引用class Album... private String title; private Artist artist; public Album(Long ID, String title, Artist artist) { super(ID); this.title = title; this.artist = artist; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Artist getArtist() { return artist; } public void setArtist(Artist artist) { this.artist = artist; }
3.2侧重主表的设计是在主对象中有一个集合类包含其所有的子对象class Team... public String Name; public IList Players { get {return ArrayList.ReadOnly(playersData);} set {playersData = new ArrayList(value);} } public void AddPlayer(Player arg) { playersData.Add(arg); } private IList playersData = new ArrayList();