// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package nosql.bdbje;

import java.io.File;

import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.Relationship;
import com.sleepycat.persist.model.SecondaryKey;

public class MultiKey {
	@Entity
	public static class Data {
		@PrimaryKey
		private int id;
		@SecondaryKey(relate=Relationship.MANY_TO_ONE)
		private String name;
		@SecondaryKey(relate=Relationship.MANY_TO_ONE)
		private String address;
		private int value;
		public Data() {
			this(0, "", "", 0);
		}
		public Data(int id, String name, String address, int value) {
			super();
			this.id = id;
			this.name = name;
			this.address = address;
			this.value = value;
		}
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
		public int getValue() {
			return value;
		}
		public void setValue(int value) {
			this.value = value;
		}
	}
	public static void main(String[] args) {
        // open database
        EnvironmentConfig envcfg = new EnvironmentConfig();
        envcfg.setAllowCreateVoid(true);
        envcfg.setTransactional(true);
        Environment env = new Environment(new File("/work/BDB"), envcfg);
        StoreConfig stcfg = new StoreConfig();
        stcfg.setAllowCreate(true);
        stcfg.setTransactional(true);
        EntityStore est = new EntityStore(env, "mulkeydb", stcfg);
        PrimaryIndex<Integer, Data> idix = est.getPrimaryIndex(Integer.class, Data.class);
        SecondaryIndex<String, Integer, Data> namix = est.getSecondaryIndex(idix, String.class, "name");
        SecondaryIndex<String, Integer, Data> addrix = est.getSecondaryIndex(idix, String.class, "address");
        // put 3 records
        idix.put(new Data(1, "A", "A A A", 123));
        idix.put(new Data(2, "B", "B B B", 456));
        idix.put(new Data(3, "C", "C C C", 789));
        // lookup by id
        System.out.println(idix.get(2).getValue());
        System.out.println(idix.get(3).getValue());
        // lookup by name
        System.out.println(namix.get("B").getValue());
        System.out.println(namix.get("C").getValue());
        // lookup by address
        System.out.println(addrix.get("B B B").getValue());
        System.out.println(addrix.get("C C C").getValue());
        // close database
        est.close();
        env.close();
	}
}
