com.webproject.checkpoint.DataRepository.java Source code

Java tutorial

Introduction

Here is the source code for com.webproject.checkpoint.DataRepository.java

Source

package com.webproject.checkpoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author qiuyue
 */
@Repository
public class DataRepository {

    @Autowired
    protected BasicDataSource dataSource;

    protected JdbcTemplate dbt;

    @PostConstruct
    public void postConstruct() {
        dbt = new JdbcTemplate(dataSource);
    }

    public void addCookie(CookieModel cookie) {
        dbt.update("INSERT INTO COOKIE (ID, EXPIREDATE) VALUES (?, ?)",
                new Object[] { cookie.getId(), cookie.getExpireDate().getTime() });
    }

    public void updateCookie(CookieModel newCookie) {
        dbt.update("UPDATE COOKIE SET EMAIL=? WHERE ID=?", new Object[] { newCookie.getMail() });
    }

    public void fillCookie(CookieModel cookie) {
        dbt.query("SELECT ID, EXPIREDATE, EMAIL FROM COOKIE WHERE ID=?", new Object[] { cookie.getId() },
                (ResultSet rs) -> {
                    while (rs.next()) {
                        cookie.setId(rs.getString(1));
                        cookie.setExpireDate(new Date(Long.parseLong(rs.getString(2))));
                        cookie.setMail(rs.getString(3));
                    }
                    return cookie;
                });
    }

    public Examine getExamine(String examineSerialNumber) {
        return dbt.query(
                "SELECT SERIALNUMBER, NUMBEROFCHALLENGE, TIMEINMILLISECOND FROM EXAMINEREPOSITORY WHERE SERIALNUMBER=?",
                new Object[] { examineSerialNumber }, (ResultSet rs) -> {
                    Examine examine = new Examine();
                    while (rs.next()) {
                        String examineClass = rs.getString(1);
                        int numberOfChallenge = rs.getInt(2);
                        long timeInMillisecond = rs.getLong(3);
                        examine.setExamineClass(examineClass);
                        examine.setNumberOfChallenge(numberOfChallenge);
                        examine.setTimeInMillisecond(timeInMillisecond);
                    }
                    return examine;
                });
    }
}