Skip to content

InSqlBox

Yong Zhu edited this page Mar 12, 2018 · 6 revisions

Use jDialects in jSqlBox

jSqlBox is a small ORM tool based on Apache-common-DbUtils and jDialects. To use jSqlBox, no need add jDialects's dependency in pom.xml because jSqlBox already included this dependency.
Demo source code:

public class TestDemo {

	@Table(name = "users")
	public static class User extends ActiveRecord {
		@UUID25
		@Id
		private String id;

		private String firstName;

		private String lastName;

		private Integer age;

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getFirstName() {
			return firstName;
		}

		public void setFirstName(String firstName) {
			this.firstName = firstName;
		}

		public String getLastName() {
			return lastName;
		}

		public void setLastName(String lastName) {
			this.lastName = lastName;
		}

		public Integer getAge() {
			return age;
		}

		public void setAge(Integer age) {
			this.age = age;
		}
	}

	@Test
	public void doTest() {
		HikariDataSource ds = new HikariDataSource();// DataSource
		ds.setDriverClassName("org.h2.Driver");
		ds.setJdbcUrl("jdbc:h2:mem:DBName;MODE=MYSQL;DB_CLOSE_DELAY=-1;TRACE_LEVEL_SYSTEM_OUT=0");
		ds.setUsername("sa");
		ds.setPassword("");

		SqlBoxContext ctx = new SqlBoxContext(ds);
		SqlBoxContext.setGlobalSqlBoxContext(ctx);
		String[] ddlArray = ctx.toDropAndCreateDDL(User.class);
		for (String ddl : ddlArray)
			ctx.quiteExecute(ddl);

		for (int i = 1; i <= 100; i++) {
			User u = new User();
			u.setFirstName("Foo" + i);
			u.setLastName("Bar" + i);
			u.setAge(i);
			u.insert();
		}
		Assert.assertEquals(100, ctx.nQueryForLongValue("select count(*) from users"));

		List<Map<String, Object>> users = ctx.nQueryForMapList(
				ctx.pagin(2, 10, "select concat(firstName, ' ', lastName) as USERNAME, age from users where age>?"),
				50);

		Assert.assertEquals(10, users.size());

		for (Map<String, Object> map : users)
			System.out.println("UserName=" + map.get("USERNAME") + ", age=" + map.get("AGE"));

		ds.close();
	}
}

Above demo used jDialects's DDL、pagination、function translate and jSqlBox's ActiveRecord。
The demo can run on different databases only need change the DataSource setting.
Full source code of the demo