简体   繁体   English

Hibernate-如何映射表示集合的对象

[英]Hibernate - How to map object that represent an collection

Sorry by the too basic question, I have no experience with Hibernate and trying to map this classes and not found an example that maps an object to another object that represents a list. 抱歉,这个问题太简单了,我没有Hibernate的经验,也没有尝试映射此类,但没有找到将一个对象映射到另一个表示列表的对象的示例。

The Keywords attribute used to be a list of String, like: 关键字属性曾经是String的列表,例如:

List<String> keywords; 

but I encapsulate it on a class to add more specialized behavior, following the book "Clean Code" from Bob C. Martin. 但是我遵循Bob C. Martin的“ Clean Code”一书将其封装在类上,以添加更多特殊的行为。 But I have no idea how to map it as if it had the same behavior when the list was in own class. 但是我不知道如何映射它,就像列表在自己的类中时一样具有相同的行为。

@Entity
@Table(name = "produtos")
public class Product {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private int id;

    @Embedded
    private BarCode barCode;

    @ManyToOne
    private Manufacturer manufacturer;

    private String description;
    //How to map?
    private Keywords keywords;

}


public class Keywords {

    private List<String> wordList = new ArrayList<>();

    public void add(String keyword) {
        wordList.add(keyword);
    }

    public boolean contains(String keyword) {
        return wordList.contains(keyword);
    }


    public static Keywords ofPhrase(String phrase) {
        Keywords keywords = new Keywords();
        StringTokenizer tokenizer = new StringTokenizer(phrase, " ", false);
        while (tokenizer.hasMoreTokens()) {
            String t = tokenizer.nextToken();
            if (t.length() > 4 && !keywords.contains(t)) {
                keywords.add(t);
            }
        }
        return keywords;
    }

    public List<String> getWordList() {
        return wordList;
    }
}

Looks like you split this member into a separate class mainly in order to add the ofPhrase() static method. 看起来您主要是为了添加ofPhrase()静态方法而将此成员拆分为一个单独的类。

I would suggest to have that method in in its own, non-JPA class, named something like KeywordTokenizer, and also to make it non-static. 我建议将该方法放在其自己的非JPA类中,该类的名称类似于KeywordTokenizer,并使其成为非静态的。 This will allow you to test the tokenizer logic in isolation and also to mock the ofPhrase() method when testing other classes that use it. 这将允许您隔离地测试令牌生成器逻辑,还可以在测试使用它的其他类时模拟ofPhrase()方法。 I think Uncle Bob would endorse this too. 我想鲍伯叔叔也会支持这一点。

More generally - in my humble experience, JPA objects should be used just to define the data structure - all that JPA annotation stuff is enough complexity to merit a class of its own. 更笼统地说-根据我的拙劣经验,应该仅将JPA对象用于定义数据结构-所有这些JPA批注内容都足够复杂,可以拥有自己的类。 Use "service" type classes such as the KeywordTokenizer suggested above to include any added logic. 使用“服务”类型的类,例如上面建议的KeywordTokenizer,以包括任何添加的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM