Convert Sql Time and Date from/to Java LocalTime and LocalDate

Food

package com.revature.model;

import java.time.LocalDate;
import java.time.LocalTime;

import lombok.Data;

@Data
public class Food {

	private int id;
	private String type;
	private LocalDate createdDate;
	private LocalTime startTime;
	private LocalTime endTime;

}

FoodDAO

package com.revature.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

import com.revature.model.Food;
import com.revature.util.ConnectionUtil;

public class FoodDAO {
	JdbcTemplate jdbcTemplate = ConnectionUtil.getJdbcTemplate();

	public void save(Food food) {

		String sql = "insert into food(type,created_date,start_time,end_time) values(?,?,?,?)";
		Object[] params = { food.getType(), food.getCreatedDate(), food.getStartTime(), food.getEndTime() };
		int rows = jdbcTemplate.update(sql, params);
		System.out.println("No of rows inserted: " + rows);

	}

	public List<Food> list() {

		String sql = "select id,type,created_date,start_time,end_time from food";
		List<Food> list = jdbcTemplate.query(sql, (rs, rowNum) -> {
			Food food = convert(rs);
			return food;
		});
		return list;

	}

	static Food convert(ResultSet rs) throws SQLException {
		Food food = new Food();
		food.setId(rs.getInt("id"));
		food.setType(rs.getString("type"));
		food.setCreatedDate(rs.getDate("created_date").toLocalDate());
		food.setStartTime(rs.getTime("start_time").toLocalTime());
		food.setEndTime(rs.getTime("end_time").toLocalTime());
		return food;
	}
}

TestFoodDAO

package com.revature.dao;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

import com.revature.model.Food;

public class TestFoodDAO {
	public static void main(String[] args) {
		Food food = new Food();
		food.setType("LUNCH");
		food.setCreatedDate(LocalDate.now());
		food.setStartTime(LocalTime.parse("11:15:00"));
		food.setEndTime(LocalTime.parse("15:00:00"));

		FoodDAO foodDAO = new FoodDAO();
		foodDAO.save(food);

		List<Food> foodList = foodDAO.list();
		for (Food f : foodList) {
			System.out.println(f);
		}

	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s