LoginSignup
0
0

More than 1 year has passed since last update.

EntityManagerをフレームワークなしで実現したい

Last updated at Posted at 2020-05-20

INSERT

とりあえずINSERTのみ。

ライブラリ未使用のJavaのみです
Enttiyにセットした内容をもとにINSERT文を取得します

プリミティブ型の初期値がすこし厄介ですが...

使うとき.java
        Entity entity = new Entity();
		entity.setId("id");
		String query = new CreateQuery<Entity>().insert(entity);
実際に作られるINSERT.sql
INSERT INTO entity ( id ) VALUES ( 'id' )
createQuery.java
package test;

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CreateQuery<T> {

	private Logger log = Logger.getLogger(this.getClass().getSimpleName());

	public String insert(T t) {
		String tableName = camelToSnake(t.getClass().getSimpleName());
		Map<String, String> data = getData(t);
		String query = "INSERT INTO " + tableName + " ( " 
				+ String.join(", ", data.keySet()) 
				+ " ) VALUES ( "
				+ String.join(", ", data.values()) + " )";
		return query;
	}
	
	private Map<String, String> getData(T t) {
		
		Map<Map<String, Object>, Class<?>> entity = new HashMap<>();
		Stream.of(t.getClass().getDeclaredFields())
		.map(v -> {
			try {
				Class<?> type = v.getType();
				String column = v.getName();
				final String flg;
				if (!boolean.class.equals(type)) {
					flg = ("get" 
							+ column.substring(0, 1).toUpperCase() 
							+ column.substring(1, column.length()));
				} else if (boolean.class.equals(type) && column.startsWith("is")) {
					String str = column.split("is")[1];
					flg = ("is" 
							+ str.substring(0, 1).toUpperCase()
							+ str.substring(1, str.length()));
				} else if (boolean.class.equals(type) && !column.startsWith("is")) {
					flg = ("is" 
							+ column.substring(0, 1).toUpperCase() 
							+ column.substring(1, column.length()));
				} else {
					flg = new String();
				}
				// invoke getter
				Object value = Stream.of(t.getClass().getDeclaredMethods())
						.filter(x -> flg.equals(x.getName()))
						.findFirst().get()
						.invoke(t);
				
				if (value == null || new Integer(0).equals(value)) {
					return null;
				}
				
				Map<Map<String, Object>, Class<?>> typedMap = new HashMap<>();
				Map<String, Object> map = new HashMap<>();
				map.put(camelToSnake(column), value);
				typedMap.put(map, type);
				return typedMap;
				
			} catch (Exception e) {
				e.printStackTrace();
				log.warning(e.getMessage());
				return null;
			}
		})
		.filter(Objects::nonNull)
		.collect(Collectors.toList())
		.forEach(entity::putAll);
		
		// create query map
		Map<String, String> data = new HashMap<>();
		for (Entry<Map<String, Object>, Class<?>> e : entity.entrySet()) {
			Class<?> type = e.getValue();
			for (Entry<String, Object> rawData : e.getKey().entrySet()) {
				String column = rawData.getKey();
				String value = new String();
				if (String.class.equals(type)) {
					value = "\'" + (String) rawData.getValue() + "\'";
				} else if (Date.class.equals(type)) {
					value = "\'" + new SimpleDateFormat("YYYY-MM-DD").format((Date) rawData.getValue()) + "\'";
				} else if (Time.class.equals(type)) {
					value = "\'" + new SimpleDateFormat("HH:MM:SS").format((Time) rawData.getValue()) + "\'";
				} else if (Timestamp.class.equals(type)) {
					value = "\'" + new SimpleDateFormat("YYYY-MM-DD HH:MM:SS").format((Timestamp) rawData.getValue()) + "\'";
				} else if (boolean.class.equals(type)){
					value = (boolean) rawData.getValue() ? "TRUE" : "FALSE";
				} else {
					value = (String) rawData.getValue();
				}
				data.put(column, value);
			}
		}
		return data;
	}

	private String camelToSnake(final String camel) {
		final StringBuilder sb = new StringBuilder(camel.length() + camel.length());
		for (int i = 0; i < camel.length(); i++) {
			final char c = camel.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append(sb.length() != 0 ? '_' : "").append(Character.toLowerCase(c));
			} else {
				sb.append(Character.toLowerCase(c));
			}
		}
		return sb.toString();
	}
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0