Search code examples
javaspring-dataaerospike

Inserting data into aerospike using aerospikeTemplate java


I am trying to insert data into aerospike. To do the same with the AerospikeClient, I wrote:

Key key = new Key("test", "myset", "mykey");
        Bin bin = new Bin("shahjahan", "k");
        aerospikeClient.put(new WritePolicy(), key, bin);

Now, I want to do the same using AerospikeTemplate. But the insert methods in AerospikeTemplate expect object as parameter, not keys and bins.

@Override
    public <T> T insert(T objectToInsert, WritePolicy policy) {
        Assert.notNull(objectToInsert, "Object to insert must not be null!");
        try {
            AerospikeData data = AerospikeData.forWrite(this.namespace);
            converter.write(objectToInsert, data);
            Key key = data.getKey();
            Bin[] bins = data.getBinsAsArray();
            client.put(policy == null ? this.insertPolicy : policy, key, bins);
        }
        catch (AerospikeException o_O) {
            DataAccessException translatedException = exceptionTranslator
                    .translateExceptionIfPossible(o_O);
            throw translatedException == null ? o_O : translatedException;
        }
        return null;
    }

I want to know that how can I pass keys and values to insert data.


Solution

  • Your object needs to have an @Id annotation to specify the key for the record. All other fields will be stored as bins. Here's an example:

    public class Product {
       @Id
       private Integer id;
       private String productId;
       private String description;
       private String imageUrl;
       private double price;
    
       ...
    }
    

    Then you just call save() on the object :

    productRepository.save(product);