2

I just found out that when I'm going to store in my mongodb, with hibernate ogm, a list this becomes a set (so no repetitions). How can I avoid it? Here's how I declared the field:

@ElementCollection private List<Double> doubles;

For example, I have this list: [0.1 0.1 0.1 0.3] When i'm going to store, it becames [0.1 0.3]

An escamotage would be to define a collection like this:

@ElementCollection private Map<Integer,Double> doubles;

But this structure is unnecessarily complex and in my case, that I have to put very long vectors, it might be a problem!

1 Answers1

0

You should be able to specify the type of the collection that Hibernate will use in the mapping.

Check out the documentation - it provides xml mapping samples, quote:

Apart from the tag as shown in Example 7.4, “Mapping a Set using ”, there is also list, map, bag, array and primitive-array mapping elements.

Also, check out Hibernate - Bag Mappings

For example in Fluent NHibernate you can use .AsBag() and .AsSet() extension methods on a mapping to indicate if you want a bag semantics, i.e. unordered sequence with duplicates.

See this blog post and this blog post for an example of using this in NHibernate

In essence, your fluent mapping could look something like this

public YourClassMap : ClassMap<YourClass>
{
  public YourClassMap()
  {
    HasMany<double>(x => x.doubles)
      .AsBag()
      .Access.CamelCaseField();
...

Your xml mapping would look something like this

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="YourNamespace" assembly="YourAssembly">
  <class name="YourClass" table="YourTableName">
  ...
    <bag name="doubles" table="Doubles">
      <one-to-many class="Double"/>
    </bag>

Sorry for providing examples only for NHibernate, this is what I work with daily, you should be able to fairly easily apply this in Hibernate as well

ironstone13
  • 3,325
  • 18
  • 24
  • Thanks, but I've never mapped an entity with XML. Although I try, I receive an error. It's a bit contorted though. After all, I ask a little. –  Jul 31 '17 at 11:46
  • @Daniel-san, could you please provide the error that you're getting? And perhaps the component mapping that you're trying to get to work. – ironstone13 Jul 31 '17 at 19:12
  • 1
    The error is in Italian but in essence it says that MyClass class> does not want attributes. We're talking about dependencies.xml, right? –  Aug 01 '17 at 09:35
  • @Daniel-san, according to the example below the mapping file should be named .hbm.xml, see https://www.tutorialspoint.com/hibernate/hibernate_bag_mapping.htm – ironstone13 Aug 01 '17 at 19:57