Read the expert written a similar QQ chat Service-side code DAO Design Summary

Source: Internet
Author: User

1, the Data Access Layer DAO design (already this project for example)

(1) First define an interface, standardize the algorithm framework. (if subclasses and base classes have a lot of common things, they should be designed as abstract classes)

Package Com.way.chat.dao

Public interface Userdao {//Registration successfully returns user Idpublic int register (user u);p ublic arraylist<user> Login (user u);p ublic arraylist<user> Refresh (int id);p ublic void logout (int id);}

(2) Define a singleton static factory method in the implementation class of the interface (avoid duplication of database operations objects) to provide a database operation object.




Import Com.way.chat.dao.userdao;public class Userdaofactory {private static <span style= "color: #ff0000;" >userda</span>o dao;public static Userdao getinstance () {if (dao = = null) {DAO = new <span style= "color: #ff000 0; " >userdaoimpl () </span>;} return DAO;}}


(3) The specific implementation class of the interface


Package Com.way.chat.dao.impl;

public class Userdaoimpl implements Userdao {@Overridepublic int register (User u) {int id; Connection con = Dbutil.connect (); String SQL1 = "INSERT into user (_name,_password,_email,_time) VALUES (?,?,?,?)"; String sql2 = "Select _id from user"; try {preparedstatement PS = con.preparestatement (SQL1);p s.setstring (1, U.getname ()); Ps.setstring (2, U.getpassword ());p s.setstring (3, U.getemail ());p s.setstring (4, MYDATE.GETDATECN ()); int res = Ps.executeupdate (); if (res > 0) {preparedstatement PS2 = con.preparestatement (SQL2); ResultSet rs = Ps2.executequery (), if (Rs.last ()) {id = rs.getint ("_id"); createfriendtable (ID);//After successful registration, create a table with the user ID as the table name. To store the friend's information return ID;}} catch (SQLException e) {e.printstacktrace ();} finally {dbutil.close (con);} return constants.register_fail;} @Overridepublic arraylist<user> Login (User u) {Connection con = dbutil.connect (); String sql = "SELECT * from user where _id=?" and _password=? "; try {preparedstatement PS = con.preparestatement (sql);p s.setint (1, U.getid ());p S.setString (2, U.getpassword ()); ResultSet rs = Ps.executequery (), if (Rs.first ()) {Setonline (U.getid ());//Update table status is online arraylist<user> refreshlist = Refresh (U.getid ()); return refreshlist;}} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);} return null;} /** * Find yourself */public user findme (int id) {User me = new User (); Connection con = Dbutil.connect (); String sql = "SELECT * from user where _id=?"; PreparedStatement Ps;try {PS = con.preparestatement (sql);p S.setint (1, id); ResultSet rs = Ps.executequery (), if (Rs.first ()) {Me.setid (Rs.getint ("_id")), Me.setemail (rs.getstring ("_email")); Me.setname (rs.getstring ("_name")); Me.setimg (Rs.getint ("_img"));} return me;} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);} return null;} /** * Refresh buddy list */public arraylist<user> refresh (int id) {arraylist<user> list = new arraylist<user> (); User me = Findme (ID); List.add (me);//First add yourself connection con = Dbutil.connect (); String sql = "Select * from _?"; PrEparedstatement Ps;try {PS = con.preparestatement (sql);p S.setint (1, id); ResultSet rs = Ps.executequery (); if (Rs.first ()) {do {user friend = new user (); Friend.setid (Rs.getint ("_qq")); Friend.setname (rs.getstring ("_name")), Friend.setisonline (Rs.getint ("_isonline")), Friend.setimg (Rs.getInt ("_img ")); Friend.setgroup (Rs.getint (" _group ")); List.add (friend);} while (Rs.next ());} return list;} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);} return null;} /** * Set Status online * * @param id */public void setonline (int id) {Connection con = dbutil.connect (); try {String sql = "Update User set _isonline=1 where _id=? "; PreparedStatement PS = con.preparestatement (sql);p S.setint (1, id);p s.executeupdate (); Updateallon (ID);//Update all table states are online} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);}} /** * After successful registration, create a user table, save the user friend * * @param id */public void createfriendtable (int id) {Connection con = dbutil.connect (); try {String sql = "CREATE TABLE _" + id+ "(_id int auto_Increment NOT NULL primary key, "+" _name varchar (a) NOT NULL, "+" _isonline int (one-by-one) not NULL default 0, "+" _group Int (11) Not NULL default 0, "+" _QQ int (one) not null default 0, "+" _img int (one-by-one) not NULL default 0) "; PreparedStatement PS = con.preparestatement (sql); int res = Ps.executeupdate (); System.out.println (res);} catch (SQLException e) {e.printstacktrace ();} finally {dbutil.close (con);}} @Override/** * downline update status is offline */public void logout (int id) {Connection con = dbutil.connect (); try {String sql = "Update user SE T _isonline=0 where _id=? "; PreparedStatement PS = con.preparestatement (sql);p S.setint (1, id);p s.executeupdate (); Updatealloff (ID);// System.out.println (res);} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);}} /** * Update all user table status offline * * @param id */public void updatealloff (int id) {Connection con = dbutil.connect (); try {String sql = "Update _?" Set _isonline=0 where _qq=? "; PreparedStatement PS = con.preparestatement (SQL), for (int offid:getallid ()) {Ps.setinT (1, Offid);p S.setint (2, id);p s.executeupdate ();}} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);}} /** * Update all user status to online * * @param id */public void Updateallon (int id) {Connection con = dbutil.connect (); try {String sql = "U Pdate _? Set _isonline=1 where _qq=? "; PreparedStatement PS = con.preparestatement (SQL), for (int onid:getallid ()) {Ps.setint (1, Onid);p S.setint (2, id); Ps.executeupdate ();}} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);}} Public list<integer> Getallid () {Connection con = dbutil.connect (); list<integer> list = new arraylist<integer> (); try {String sql = "Select _id from User"; PreparedStatement PS = con.preparestatement (SQL); ResultSet rs = Ps.executequery (), if (Rs.first ()) {do {int id = rs.getint ("_id"), List.add (ID);} while (Rs.next ());} SYSTEM.OUT.PRINTLN (list); return list;} catch (SQLException e) {//E.printstacktrace ();} finally {dbutil.close (con);} return null;} public static void Main (String[] args) {User U = new User (); Userdaoimpl dao = new Userdaoimpl ();//U.setid ()//U.setname ("QQ");//U.setpassword ("123");//U.setemail ("[email& Nbsp;protected]);//System.out.println (Dao.register (U))///System.out.println (Dao.login (U));///Dao.logout ( ///Dao.setonline,///Dao.getallid (); list<user> list = Dao.refresh (2016); SYSTEM.OUT.PRINTLN (list);}}



(4) The database uses the properties file to load the tool class that drives the close connection:


public class Dbutil {/** * Connection database * * @return database Connection object */public static Connection connect () {Properties Pro = new Propertie S (); String driver = null; String URL = null; String username = null; String Password = null;try {InputStream is = DButil.class.getClassLoader (). getResourceAsStream ("db.properties");// System.out.println (Is.tostring ());p ro.load (IS);d river = Pro.getproperty ("driver"); URL = pro.getproperty ("url"); Username = Pro.getproperty ("username");p assword = pro.getproperty ("password");//SYSTEM.OUT.PRINTLN (Driver + ":" + URL + ":" + Username + ":"//+ password); Class.forName (driver); Connection conn = drivermanager.getconnection (URL, username,password); return conn;} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} catch ( ClassNotFoundException e) {e.printstacktrace ();} catch (SQLException e) {e.printstacktrace ();} return null;} /** * Close Database * * @param conn * Incoming database connection object */public static void Close (Connection con) {if (con! = nulL) {try {con.close ();} catch (SQLException e) {e.printstacktrace ()}}} public static void Main (string[] args) {//connection con = new Dbutil (). connect ();//system.out.println (con);//}}


Corresponding configuration file: Db.properties

driver=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/qq?useunicode=true&characterencoding= Utf-8username=rootpassword=admin





Read the expert written a similar QQ chat Service-side code DAO Design Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.