Giter VIP home page Giter VIP logo

johm's Introduction

JOhm

JOhm is a blazingly fast Object-Hash Mapping library for Java inspired by the awesome Ohm. The JOhm OHM is a modern-day avatar of the old ORM's like Hibernate with the difference being that we are not dealing with an RDBMS here but with a NoSQL rockstar.

JOhm is a library for storing objects in Redis, a persistent key-value database. JOhm is designed to be minimally-invasive and relies wholly on reflection aided by annotation hooks for persistence. The fundamental idea is to allow large existing codebases to easily plug into Redis without the need to extend framework base classes or provide excessive configuration metadata.

Durable data storage is available via the Redis Append-only file (AOF). The default persistence strategy is Snapshotting.

About this fork

The original JOhm is not maintained anymore, there's a lot of useful pull requests that are not being merged and the author is not responding.

I need JOhm in my projects, so I forked it and will maintain it here. Go ahead if you have pull requests to merge from the original repository, I will merge them asap.

I've already added support for enums, dates and some improvements like ignoring some field retrieval. I also already merged PR 39 which is useful for querying on multiple fields at the same time.

CHANGELOG

Use this fork

I will release a version of this JOhm fork every time I fix a bug or merge a PR. In order to use this fork you need to add a custom maven repository in your pom.xml:

<repositories>
    <repository>
        <id>johm-mvn-repo</id>
        <url>https://raw.github.com/agrison/johm/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Then just add the dependency to this JOhm version, last released version is currently 0.6.7 (last snapshot is 0.6.8-SNAPSHOT):

<dependency>
    <groupId>redis</groupId>
    <artifactId>johm</artifactId>
    <version>0.6.7</version>
    <type>jar</type>
</dependency>

JOhm currently uses Jedis 2.8.0

What can I do with JOhm?

JOhm is still in active development. The following features are currently available:

  • Basic attribute persistence (String, Integer, etc...)
  • Enums
  • Auto-numeric Ids
  • References
  • Arrays
  • Indexes
  • Deletion
  • List, Set, SortedSet and Map relationship
  • Search on attributes, arrays, collections and references

Stay close! It is growing pretty fast!

How do I use it?

And this is a small example (getters and setters are not included for the sake of simplicity):

@Model
class User {
    @Id
    private Long id;
	@Attribute
	private String name;
	@Attribute
	@Indexed
	private int age;
	@Reference
	@Indexed
	private Country country;
	@CollectionList(of = Comment.class)
	@Indexed
	private List<Comment> comments;
	@CollectionSet(of = Item.class)
	@Indexed
	private Set<Item> purchases;
	@CollectionMap(key = Integer.class, value = Item.class)
    @Indexed
    private Map<Integer, Item> favoritePurchases;
    @CollectionSortedSet(of = Item.class, by = "price")
    @Indexed
    private Set<Item> orderedPurchases;
    @Array(of = Item.class, length = 3)
    @Indexed
    private Item[] threeLatestPurchases;
}

// The value() of @Model can be used to use a specific key in redis
// If not set then the Java Class<?>.getSimpleName() is used as default
@Model("Com")
class Comment {
    @Id
    private Long id;
	@Attribute
	private String text;
	@Attribute
	private Status status;
}

@Model
class Item {
    @Id
    private Long id;
	@Attribute
	private String name;
}

enum Status {
    WAITING_FOR_MODERATION, VALID, FLAGGED
}

Initiating JOhm:

JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(), "localhost");
JOhm.setPool(jedisPool);

Creating a User and persisting it:

User someOne = new User();
someOne.setName("Someone");
someOne.setAge(30);
JOhm.save(someOne);

Loading a persisted User:

User storedUser = JOhm.get(User.class, 1);

You can avoid properties being loaded:

User userWithoutComments = JOhm.get(User.class, 1, "comments");

Checking if a User exists:

boolean user2Exists = JOhm.exists(User.class, 42);

Deleting a User:

JOhm.delete(User.class, 1);

Search for all users of age 30:

List<User> users = JOhm.find(User.class, "age", "30");

Search for all users of age 30, without returning their favorite purchases:

List<User> users = JOhm.find(User.class, "age", "30", "favoritePurchases");

Model with a reference:

User someOne = new User();
...
JOhm.save(someOne);

Country someCountry = new Country();
...
JOhm.save(country);

someOne.setCountry(someCountry);

Model with a list of nested models:

User someOne = new User();
...
JOhm.save(someOne);

Comment aComment = new Comment();
...
JOhm.save(aComment);

someOne.getComments().add(aComment);

Model with a set of nested models:

User someOne = new User();
...
JOhm.save(someOne);
	
Item anItem = new Item();
...
JOhm.save(anItem);
	
someOne.getPurchases().add(anItem);

For more usage examples check the tests.

And you are done!

How do I use it with Spring?

applicationContext.xml

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
	<property name="minIdle" value="1" />
	<property name="maxIdle" value="8" />
</bean>

<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
	<constructor-arg index="0" ref="poolConfig" />
	<constructor-arg index="1" value="localhost" />
	<constructor-arg index="2" value="6379" />
	<constructor-arg index="3" value="2000" />
</bean>

<bean id="redisOhm" class="redis.clients.johm.JOhm" factory-method="setPool" scope="singleton" >
	<constructor-arg ref="jedisPool" />
</bean>

<bean id="userDao" class="com.mypackage.UserDaoImpl" />

And now you can use directly in your UserDaoImpl:

JOhm.expire(entity, seconds);

License

Copyright (c) 2010 Gaurav Sharma and Jonathan Leibiusky

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

johm's People

Contributors

agrison avatar gsharma avatar dpoldrugo avatar josepaiva94 avatar tahseen avatar

Stargazers

FAP avatar Armel Soro avatar Jovel avatar Nicholas Marshall avatar Petr avatar Julian avatar Jordan Culver avatar 4Dim avatar Tristan Stanley avatar Danny Im avatar Alan Kash avatar Marc Savy avatar STB Land avatar Inacio avatar HQM avatar Arturo Zendrera Valsecchi avatar Rui Gu avatar Glade Luco avatar Philippe Charrière avatar Javen Fang avatar Gowthaman Basuvaraj avatar Victorio Cebedo II avatar

Watchers

Gowthaman Basuvaraj avatar  avatar James Cloos avatar Lichuan avatar  avatar Jordan Culver avatar  avatar

johm's Issues

List fields of objects not being persisted with objects

I'm trying to persist list fields, and they're not being persisted. It's as if I haven't even added the annotations to the list field. As far as annotations go, my models are almost exactly similar to the models in the test folder with differences in class names and the addition of the Hibernate annotations:

Item model:

@Model("item")
@Entity
@Table(name="item")
public class Item implements Serializable{

    @redis.clients.johm.Id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private long mId;

    @Attribute
    @Column(name="date_created")
    private Date mDateCreated;

    @CollectionList(of = Update.class)
    @Indexed
    @OneToMany(mappedBy="mItem", fetch=FetchType.EAGER)
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.REMOVE})
    private List<Updates> mUpdates;

    public List<Update> getUpdates() {
            return mUpdates;
    }

    public void setUpdates(List<Update> updates) {
            mUpdates = updates;
    }
}

Update model:

@Model("update")
@Entity
@Table(name="update")
public class Update implements Serializable {

    @redis.clients.johm.Id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private long mId;

    @Attribute
    @Column(name="date_created")
    private Date mDateCreated;
}

I tested persisting the item with this code first:
*the Hibernate query is definitely retrieving an Item with an mUpdates field containing two Update objects, both containing Date objects in their mDateCreated field

public void doThis() throws InterruptedException{
        Session session = HibernateUtils.openSession();
        session.beginTransaction();

        Item item= (Item) session.createQuery("FROM Item WHERE mId = 100").uniqueResult();

        session.getTransaction().commit();
        session.close();

        JOhm.save(item);
    }

The Item object was being saved as hash item:100 and the item:all set was also being saved. But the hash was without the List<Update> mUpdates field, and the individual update:<id> hashes were not being persisted either. There was no sign of an Update object in the redis database at all.

I then thought that maybe JOhm didn't persist List fields along with the object they're contained in, but each object has to be saved individually and then the members of the List had to be added to the object's list like in persistList() in CollectionsTest.java. So, I then tried this next code because it was more similar to the way it was done in your test method; aside from the Hibernate query:

public void doThis() throws InterruptedException{
        //same hibernate query as before
        Session session = HibernateUtils.openSession();
        session.beginTransaction();

        Item item = (Item) session.createQuery("FROM Item WHERE mId = 100").uniqueResult();

        session.getTransaction().commit();
        session.close();

        List<Update> updates = item.getUpdates();

        item.setUpdates(new ArrayList<>());

        for (Update update : updates){
            JOhm.save(update);
        }

        JOhm.save(item);

        for (Update update : updates){
            item.getUpdates().add(update);
        }
    }

After this code, all the Update objects were being saved to the database, but there was no indication that they were linked to the Item object that was saved -- no mUpdates field in item:100 hash.

Any idea of what I may be doing wrong?

JOhm.save() error: EXECABORT Transaction discarded because of previous errors

Was just testing out JOhm for the first time with JOhm.save():

public void doThis() {
        Item item = new Item(100);

        JOhm.save(item);
 }

When I got this exception:
*I'm pretty sure this is an issue with JOhm because I can save to the Redis database successfully using Jedis.set() and Jedis.hmset()

redis.clients.jedis.exceptions.JedisDataException: EXECABORT Transaction discarded because of previous errors.
    at redis.clients.jedis.Protocol.processError(Protocol.java:117)
    at redis.clients.jedis.Protocol.process(Protocol.java:142)
    at redis.clients.jedis.Protocol.read(Protocol.java:196)
    at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:288)
    at redis.clients.jedis.Connection.getRawObjectMultiBulkReply(Connection.java:233)
    at redis.clients.jedis.Connection.getObjectMultiBulkReply(Connection.java:239)
    at redis.clients.jedis.Transaction.exec(Transaction.java:38)
    at redis.clients.jedis.BinaryJedis.multi(BinaryJedis.java:1632)
    at redis.clients.johm.Nest.multi(Nest.java:117)
    at redis.clients.johm.JOhm.save(JOhm.java:321)
    at redis.clients.johm.JOhm.save(JOhm.java:224)
    at org.pollinator.DoClass.doThis(DoClass.java:66)

Here is the Item class:
*also a Hibernate model class

@Model
@Entity
@Table(name="item")
public class Poll implements Serializable{

    @redis.clients.johm.Id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private long mId;

    public Item(){
    }

    public Item(long id){
        mId = id;
    }
}

After doThis() is called, the item's id is added to a set in the Redis database called Item:all before the exception is thrown, but that's all that is created -- I flushed the redis database before calling doThis(). Anyone ever experience a similar issue?

Deleted models leave behind their Collection keys.

I'm using Redis Desktop Manager to look at the stored keys and noticed that JOhm was leaving behind a bunch of orphaned keys after the parent objects were being deleted. They all seemed to be Collection indexes.

Test case:

@Model
public class Test {
    @Id
    public Long id;
    @Attribute
    public String name;
    @CollectionList(of = TestMessage.class)
    public List<TestMessage> messages;
}

@Model
public class TestMessage {
    @Id
    public Long id;
    @Attribute
    public String message;
}

Test test = new Test();
test.name = "Test";
JOhm.save(test);

TestMessage testMessage = new TestMessage();
testMessage.message = "HelloWorld";
JOhm.save(testMessage);
test.messages.add(testMessage);

JOhm.delete(Test.class, test.id, true, true);

String key = String.format("Test:%d:messages", test.id);
boolean keyexists = _jedisPool.getResource().exists(key);
LOGGER.info(String.format("Key Exists: %s", keyexists?"YES":"NO"));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.