栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

行为类似于@Entity和@Embeddable的类

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

行为类似于@Entity和@Embeddable的类

以下解决方案显示了一个由玩家组成的复合键,该键由团队和该团队中的玩家列表中的位置组成。从团队到球员节省级联。

Team.java

import java.io.Serializable;import java.util.ArrayList;import java.util.List;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Version;import org.apache.commons.lang.builder.ToStringBuilder;import org.apache.commons.lang.builder.ToStringStyle;import org.hibernate.annotations.IndexColumn;@Entitypublic class Team implements Serializable {    @Id @GeneratedValue private Long id;    @Version private int version;    @oneToMany(cascade=CascadeType.ALL, mappedBy="id.team")    @IndexColumn(name="PLAYER_IDX")    private List<Player> players = new ArrayList<Player>();    private String name;    protected Team() {}    public Team(String name) {        this.name = name;    }    public boolean addPlayer(Player player) {        boolean result = players.add(player);        if (result) { player.setPlayerId(new PlayerId(this, players.size() - 1));        }        return result;    }    public List<Player> getPlayers() {        return players;    }    @Override    public String toString() {        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("name", name).append("players", players).toString();    }}

播放器

import java.io.Serializable;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Version;import org.apache.commons.lang.builder.ToStringBuilder;import org.apache.commons.lang.builder.ToStringStyle;@Entitypublic class Player implements Serializable {    @Id private PlayerId id;    @Version private int version;    void setPlayerId(PlayerId id) {        this.id = id;    }    @Override    public String toString() {        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("number", id.getNumber()).toString();    }}

PlayerId.java

import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Embeddable;import javax.persistence.ManyToOne;import org.apache.commons.lang.builder.HashCodeBuilder;@Embeddablepublic class PlayerId implements Serializable {    @ManyToOne    private Team team;    @Column(name="PLAYER_IDX", insertable=false, updatable=false)    private int number;    protected PlayerId() {}    PlayerId(Team team, int number) {        this.team = team;        this.number = number;    }    public int getNumber() {        return number;    }    @Override    public boolean equals(Object obj) {        if (obj == null) { return false;        } else if (obj == this) { return true;        } if (obj instanceof PlayerId) { PlayerId other = (PlayerId) obj; return other.team.equals(this.team) && other.number == this.number;         }        return false;    }    @Override    public int hashCode() {        return new HashCodeBuilder().append(team).append(number).toHashCode();    }}

此测试如下:

public void testPersistTeamAndPlayers() throws Exception {    Team team = new Team("My Team");    team.addPlayer(new Player());    team.addPlayer(new Player());    AnnotationConfiguration configuration = new AnnotationConfiguration();    configuration.addAnnotatedClass(Team.class);    configuration.addAnnotatedClass(Player.class);    configuration.configure();    SessionFactory sessionFactory = configuration.buildSessionFactory();    Session session;    session = sessionFactory.openSession();    Transaction transaction = session.beginTransaction();    session.save(team);    transaction.commit();    session.close();    session = sessionFactory.openSession();    @SuppressWarnings("unchecked") List<Team> list = session.createCriteria(Team.class).list();    assertEquals(1, list.size());    Team persisted = list.get(0);    System.out.println(persisted);

给出以下日志输出:

12:37:17,796 DEBUG [SchemaExport, SchemaExport.execute]     create table Player (        PLAYER_IDX integer not null,        version integer not null,        team_id bigint,        primary key (PLAYER_IDX, team_id)    )12:37:17,796 DEBUG [SchemaExport, SchemaExport.execute]     create table Team (        id bigint generated by default as identity (start with 1),        name varchar(255),        version integer not null,        primary key (id)    )12:37:17,796 DEBUG [SchemaExport, SchemaExport.execute]     alter table Player         add constraint FK8EA38701AA5DECBA         foreign key (team_id)         references Team12:37:17,812 INFO  [SchemaExport, SchemaExport.importscript] Executing import script: /import.sql12:37:17,812 INFO  [SchemaExport, SchemaExport.execute] schema export complete12:37:17,859 DEBUG [SQL, SQLStatementLogger.logStatement]     insert     into        Team        (id, name, version)     values        (null, ?, ?)12:37:17,875 DEBUG [SQL, SQLStatementLogger.logStatement]     call identity()12:37:17,875 DEBUG [SQL, SQLStatementLogger.logStatement]     select        player_.PLAYER_IDX,        player_.team_id,        player_.version as version1_     from        Player player_     where        player_.PLAYER_IDX=?         and player_.team_id=?12:37:17,890 DEBUG [SQL, SQLStatementLogger.logStatement]     select        player_.PLAYER_IDX,        player_.team_id,        player_.version as version1_     from        Player player_     where        player_.PLAYER_IDX=?         and player_.team_id=?12:37:17,890 DEBUG [SQL, SQLStatementLogger.logStatement]     insert     into        Player        (version, PLAYER_IDX, team_id)     values        (?, ?, ?)12:37:17,890 DEBUG [SQL, SQLStatementLogger.logStatement]     insert     into        Player        (version, PLAYER_IDX, team_id)     values        (?, ?, ?)12:37:17,906 DEBUG [SQL, SQLStatementLogger.logStatement]     select        this_.id as id0_0_,        this_.name as name0_0_,        this_.version as version0_0_     from        Team this_12:37:17,937 DEBUG [SQL, SQLStatementLogger.logStatement]     select        players0_.team_id as team3_1_,        players0_.PLAYER_IDX as PLAYER1_1_,        players0_.PLAYER_IDX as PLAYER1_1_0_,        players0_.team_id as team3_1_0_,        players0_.version as version1_0_     from        Player players0_     where        players0_.team_id=?Team[name=My Team,players=[Player[number=0], Player[number=1]]]

最后一行显示

toString
for
Team
Player
,它显示如何分配数字(列表的索引)。其他实体可以引用玩家(通过team_id和player_idx)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/447593.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号