The story of making dto, dao-like with java, sqlite

Hello, this is a certain company engineer. A memorandum because I made dto, dao-like when making a task management application with swing, java. Click here for related past articles ↓ https://qiita.com/Ohtak/items/1be20a4b06b5833c3d61 https://qiita.com/Ohtak/items/f9a47b9be26c93fedaf9

1. Code

First from the dto file. I haven't done anything different, though ...

TaskDto.java


public class TaskDto {

	//Task ID
	Integer id;
	
	//Task name
	String title;
	
	//Task remarks
	String discription;
	
	//Task deadline
	String limitDate;
	
	//Task status
	Integer status;
	
	/**
	 * @return id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @param id set id
	 */
	public void setId(Integer id) {
		this.id = id;
	}
	
	/**
	 * @return title
	 */
	public String getTitle() {
		return title;
	}

	/**
	 * @param title set title
	 */
	public void setTitle(String title) {
		this.title = title;
	}
	
	/**
	 * @return discription
	 */
	public String getDiscription() {
		return discription;
	}

	/**
	 * @param discription set discription
	 */
	public void setDiscription(String discription) {
		this.discription = discription;
	}
	
	/**
	 * @return title
	 */
	public String getLimitDate() {
		return limitDate;
	}

	/**
	 * @param title set title
	 */
	public void setLimitDate(String limitDate) {
		this.limitDate = limitDate;
	}
	
	/**
	 * @return status
	 */
	public Integer getStatus() {
		return status;
	}

	/**
	 * @param status set status
	 */
	public void setStatus(Integer status) {
		this.status = status;
	}
}

That's it.

Next is dao. I don't look like dao so much, so I give it a selfish class name.

DBAccesser.java


public class DBAccesser {
	public Connection con = null;
	public Statement smt = null;
	
	public List<TaskDto> selectAll(){
		try {
    		//Created if not connected to the database
    		con = DriverManager.getConnection("jdbc:sqlite:/Users/taskManager.sqlite");
    		smt = con.createStatement();
    		String sql = "select * from task";
    		ResultSet rs = smt.executeQuery(sql);
    		List<TaskDto> tasks = new ArrayList<TaskDto>();
    		while( rs.next() ) {
    			TaskDto task = new TaskDto();
    			task.setId(rs.getInt(1));
        		task.setTitle(rs.getString(2));
        		task.setDiscription(rs.getString(3));
        		task.setLimitDate(rs.getString(4));
        		task.setStatus(rs.getInt(5));
        		tasks.add(task);
    		}
    		con.close();
    		return tasks;
    	}
		catch (SQLException e) {
    		//TODO auto-generated catch block
    		e.printStackTrace();
    		return null;
    	}
	}
	
	public int selectLastId(){
		try {
    		//Created if not connected to the database
    		con = DriverManager.getConnection("jdbc:sqlite:/Users/taskManager.sqlite");
    		smt = con.createStatement();
    		String sql = "select id from task order by id desc limit 1";
    		ResultSet rs = smt.executeQuery(sql);
    		int id = rs.getInt(1);
    		con.close();
    		return id;
    	}
		catch (SQLException e) {
    		//TODO auto-generated catch block
    		e.printStackTrace();
    		return 0;
    	}
	}
	
	public void insert(TaskDto task){
		try {
    		//Connect to database
    		con = DriverManager.getConnection("jdbc:sqlite:/Users/taskManager.sqlite");
    		smt = con.createStatement();
    		String sql = "insert into task (id, name, limit_date, comment) values(" + String.valueOf(task.getId()) + ", '" + task.getTitle() + "', '" + task.getLimitDate() + "', '" + task.getDiscription() + "');";
    		smt.executeUpdate(sql);
    		con.close();
    	} catch (SQLException e) {
    		//TODO auto-generated catch block
    		e.printStackTrace();
    	}
	}
	
	public void update(TaskDto task){
		try {
			//Connect to database
			con = DriverManager.getConnection("jdbc:sqlite:/Users/taskManager.sqlite");
			smt = con.createStatement();
			String sql = "update task set name='"+ task.getTitle() + "', limit_date='" + task.getLimitDate() + "', comment='"+ task.getDiscription() + "', status = " + task.getStatus() + " where id=" + task.getId() + ";";
			smt.executeUpdate(sql);
			con.close();
		} catch (SQLException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void delete(int id){
		try {
			//Connect to database
			con = DriverManager.getConnection("jdbc:sqlite:/Users/taskManager.sqlite");
			smt = con.createStatement();
			String sql = "DELETE FROM task WHERE id=" + id + ";";
			smt.executeUpdate(sql);
			con.close();
		} catch (SQLException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
		}
	}
}

In addition to the four basic methods, there is only one original method. I haven't done that difficult here either. I just did it according to the sqlite manual.

2. Caller

It looks like this when calling.

taskRegisterPanel.java


DBAccesser dbAccesser = new DBAccesser();
TaskDto task = new TaskDto();
task.setId(Integer.parseInt(taskId.getText()));
task.setTitle(taskTitle.getText());
task.setLimitDate(taskLimit.getText());
task.setDiscription(taskDiscription.getText());
task.setStatus(0);
dbAccesser.update(task);

This is also easy.

3. Impressions

The advantage of using this is that it makes it easier for the caller to call the operations together. It's easy to do above because I'm using it. It was very annoying because I didn't use it at first ...

By using the dto file, you can easily operate the arguments and results when accessing the DB.

The more I write it, the more I feel it now, but I will continue to do my best.

Recommended Posts

The story of making dto, dao-like with java, sqlite
The story of making ordinary Othello in Java
The story of making a game launcher with automatic loading function [Java]
The story of making a reverse proxy with ProxyServlet
[Java version] The story of serialization
A story about hitting the League Of Legends API with JAVA
The story of writing Java in Emacs
The story of low-level string comparison in Java
The story of learning Java in the first programming
The story of making the existing Dockerfile GPU compatible
The story of tuning android apps with libGDX
Calculate the similarity score of strings with JAVA
The story of making an electronic New Year's card app with Vue.js + Rails
CI the architecture of Java / Kotlin applications with ArchUnit
Monitor the internal state of Java programs with Kubernetes
Check the behavior of Java Intrinsic Locks with bpftrace
The story of making Dr. Oakid using LINE BOT
Replace only part of the URL host with java
20190803_Java & k8s on Azure The story of going to the festival
A story packed with the basics of Spring Boot (solved)
[Java] Simplify the implementation of data history management with Reladomo
The story of pushing Java to Heroku using the BitBucket pipeline
Be sure to compare the result of Java compareTo with 0
The story of building a Java version of Minecraft server with GCP (and also set a whitelist)
The story of the first Rails app refactored with a self-made helper
[Java] Delete the elements of List
[Java1.8 +] Get the date of the next x day of the week with LocalDate
The story of not knowing the behavior of String by passing Java by reference
Story of passing Java Gold SE8
Try Hello World with the minimum configuration of Heroku Java spring-boot
The story of @ViewScoped consuming memory
The story of toString () starting with passing an array to System.out.println
Follow the link with Selenium (Java)
The point of addiction when performing basic authentication with Java URLConnection
Impressions of making BlackJack-cli with Ruby
The story of making a communication type Othello game using Scala.
Overwrite upload of file with the same name with BOX SDK (java)
Is the version of Elasticsearch you are using compatible with Java 11?
The origin of Java lambda expressions
The story of making it possible to build a project that was built by Maven with Ant
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
The story of forgetting to close a file in Java and failing
Let's express the result of analyzing Java bytecode with a class diagram
The story of acquiring Java Silver in two months from completely inexperienced.
Check the domain by checking the MX record of the email address with java
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
The story of encountering Spring custom annotation
Get the result of POST in Java
Story of paiza.jp [Java standard input solution]
Check the contents of the Java certificate store
Check the contents of params with pry
Examine the memory usage of Java elements
Memo: [Java] Check the contents of the directory
The story of updating SonarQube's Docker Container
Compare the elements of an array (Java)
The story of RxJava suffering from NoSuchElementException
The story of AppClip support in Anyca
What are the updated features of java 13
Easily measure the size of Java Objects
Looking back on the basics of Java
About the treatment of BigDecimal (with reflection)