Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.j256.ormlite.examples.manytomany;
  
  import static org.junit.Assert.assertEquals;
  
  import java.util.List;
  
Main sample routine to show how to do many-to-many type relationships. It also demonstrates how we user inner queries as well foreign objects.

NOTE: We use asserts in a couple of places to verify the results but if this were actual production code, we would have proper error handling.

 
 public class ManyToManyMain {
 
 	// we are using the in-memory H2 database
 	private final static String DATABASE_URL = "jdbc:h2:mem:manytomany";
 
 	private Dao<UserIntegeruserDao;
 	private Dao<PostIntegerpostDao;
 
 	public static void main(String[] argsthrows Exception {
 		// turn our static method into an instance of Main
 		new ManyToManyMain().doMain(args);
 	}
 
 	private void doMain(String[] argsthrows Exception {
 		JdbcConnectionSource connectionSource = null;
 		try {
 			// create our data-source for the database
 			connectionSource = new JdbcConnectionSource();
 			// setup our database and DAOs
 			setupDatabase(connectionSource);
 			// read and write some data
 			..println("\n\nIt seems to have worked\n\n");
 		} finally {
 			// destroy the data source which should close underlying connections
 			if (connectionSource != null) {
 				connectionSource.close();
 			}
 		}
 	}

Setup our database and DAOs
 
 	private void setupDatabase(ConnectionSource connectionSourcethrows Exception {

Create our DAOs. One for each class and associated table.
 
 		 = DaoManager.createDao(connectionSourceUser.class);
 		 = DaoManager.createDao(connectionSourcePost.class);
 		 = DaoManager.createDao(connectionSourceUserPost.class);

Create the tables for our example. This would not be necessary if the tables already existed.
 
 		TableUtils.createTable(connectionSourceUser.class);
 		TableUtils.createTable(connectionSourcePost.class);
 		TableUtils.createTable(connectionSourceUserPost.class);
 	}

Read and write some example data.
 
 	private void readWriteData() throws Exception {
 
 		// create our 1st user
 		User user1 = new User("Jim Coakley");
 
 		// persist the user object to the database
 		.create(user1);
 
 		// have user1 post something
 		Post post1 = new Post("Wow is it cold outside!!");
 		// save the post to the post table
 		.create(post1);
 
 		// link the user and the post together in the join table
 		UserPost user1Post1 = new UserPost(user1post1);
 		.create(user1Post1);
 
 		// have user1 post a second post
 		Post post2 = new Post("Now it's a bit warmer thank goodness.");
		UserPost user1Post2 = new UserPost(user1post2);
		.create(user1Post2);
		// create another user
		User user2 = new User("Rose Gray");
		// have the 2nd user also say the 2nd post
		UserPost user2Post1 = new UserPost(user2post2);
		.create(user2Post1);
		/*
		 * Now go back and do various queries to look things up.
		 */
		/*
		 * show me all of a user's posts:
		 */
		// user1 should have 2 posts
		List<Postposts = lookupPostsForUser(user1);
		assertEquals(2, posts.size());
		assertEquals(post1.idposts.get(0).);
		assertEquals(post1.contentsposts.get(0).);
		assertEquals(post2.idposts.get(1).);
		assertEquals(post2.contentsposts.get(1).);
		// user2 should have only 1 post
		posts = lookupPostsForUser(user2);
		assertEquals(1, posts.size());
		assertEquals(post2.contentsposts.get(0).);
		/*
		 * show me all of the users that have a post.
		 */
		// post1 should only have 1 corresponding user
		List<Userusers = lookupUsersForPost(post1);
		assertEquals(1, users.size());
		assertEquals(user1.idusers.get(0).);
		// post2 should have 2 corresponding users
		users = lookupUsersForPost(post2);
		assertEquals(2, users.size());
		assertEquals(user1.idusers.get(0).);
		assertEquals(user1.nameusers.get(0).);
		assertEquals(user2.idusers.get(1).);
		assertEquals(user2.nameusers.get(1).);
	}
	/*
	 * Convenience methods to build and run our prepared queries.
	 */
	private List<PostlookupPostsForUser(User userthrows SQLException {
		if ( == null) {
		}
	}
	private List<UserlookupUsersForPost(Post postthrows SQLException {
		if ( == null) {
		}
	}

Build our query for Post objects that match a User.
		// build our inner query for UserPost objects
		// just select the post-id field
		SelectArg userSelectArg = new SelectArg();
		// you could also just pass in user1 here
		userPostQb.where().eq(.userSelectArg);
		// build our outer query for Post objects
		// where the id matches in the post-id from the inner query
		postQb.where().in(.userPostQb);
		return postQb.prepare();
	}

Build our query for User objects that match a Post
		// this time selecting for the user-id field
		SelectArg postSelectArg = new SelectArg();
		userPostQb.where().eq(.postSelectArg);
		// build our outer query
		// where the user-id matches the inner query's user-id field
		userQb.where().in(.userPostQb);
		return userQb.prepare();
	}
New to GrepCode? Check out our FAQ X