Java backend mock interview question set ④

1. Please introduce yourself first.

Hello, interviewer, my name is ***, from **, graduated from ****** university, I am a ******* major *recruitment* undergraduate. Today I am mainly here to interview for the Java back-end development engineer position in your company.

The major courses in the university are Java, Python, digital image processing, and JavaEE.

During college, I scored 460 points in English level 6, participated in Huawei Cloud competition, and won the third prize in the National College Green Computing Series Competition.

The technology stacks I am familiar with are listed on my resume. I think my highlights are the following: being able to perform simple JVM tuning; having experience in actually dealing with high concurrency problems; being familiar with MySQL operations and understanding the principles of database tuning. ; Familiar with the basic operations of Linux.

I taught myself C# for two weeks and listened to the school's explanation of Python's Django framework for two weeks, and I wrote a simple project. In half a year, I developed an image encryption algorithm and published it as my graduation thesis. After studying Java for one semester and self-study for 2 months, I made these two Java projects in school-enterprise cooperation projects.

He has led a team to develop a Django framework project and participated in two Java projects in school-enterprise cooperation.

I understand that your company's business needs are biased toward xxx, and I happen to be good at xxx, so I came to apply for the Java development position in your company.

(or connection)

I understand that your company's business needs are biased toward xxx. I recently worked on a xx project, which happens to be xxx. Do you need to give a brief project introduction?

2. Tell me about this IoC and AOP

IoC: (Inverse of Control) Inversion of Control, also called DI dependency injection, refers to handing over the creation rights of objects to the Spring container for creation. (Then give examples of wheels and cars)

In fact, there are many ways of IoC. Not only is the most commonly used Bean injection in Spring technology, but also the construction method and Setter method implementation.

AOP: (Aspect Oriented Programming) Aspect-oriented programming can enhance the functions of specific services in Spring and can implement authentication or public field filling services.

There are two main ways of dynamic proxy, JDK dynamic proxy and CGLIB dynamic proxy.

SpringMVC uses third-level cache instead of second-level cache. One of the reasons is to facilitate the use of AOP.

Regarding SpringMVC’s use of third-level cache, I can tell you here...

Regarding the public field filling we use AOP to do, I can tell you here...

3.Have you ever understood JWT? Have you ever used it?

I know it, it has been useful.

JWT is JSON Web Token, which is a relatively easy-to-use authentication technology after Cookie and Session.

Cookies are a technology supported by the HTTP protocol, which is its advantage.

But its shortcomings are also obvious. It does not support mobile APPs, such as Android and IOS; the second point is that it is not safe, and users can disable cookies; the third point is that it cannot cross domains.

Session is a cookie-based server session tracking technology. The advantage is that it is stored on the server side and is safe.

The shortcomings are also obvious, because it is based on cookies, and it has all the problems that come with cookies: mobile APP cannot be used, users can disable it, and cannot cross domains; in addition, it cannot be used with clustered servers; it Also takes up server memory.

The JWT technology commonly used by enterprises perfectly solves the above problems. It works on both PC and mobile terminals; it can also be used in a cluster; it does not require server storage and does not put storage pressure on the server.

If there is any disadvantage to it, it is that you need to implement it yourself.

So how to achieve it? We add JWT to our login process like this:

First, access the login interface in the browser. After verifying that the user has successfully logged in, our backend generates a JWT token and returns the JWT token to the frontend.

The front end saves the JWT token after getting it, and the request headers of subsequent requests will carry this.

Then the back-end unified interception checks this JWT and completes the verification.

A JWT token consists of three parts:

Header, records token type, signature algorithm, etc. For example:{"alg":"HS256","type":"JWT"}

Payload payload carries some custom information, default information, etc. For example:{"id":"1","username":"Tom"}

Signature signature prevents Token from being tampered with and ensures security. Add the header and payload to the specified secret key and calculate it through the specified signature algorithm.

4.Have you ever used es? How did you use it?

We used es. In my takeout project, in order to provide the merchant search function, we designed the es search process.

First of all, the four aspects of the basic search interface are: the request method is POST, the request path is /shopSearch/list, the request parameters include keywords, page number, paging size, sorting method, and the return value is the page result class.

First define the Controller;

Then prepare to set up the Java language client officially provided by ES, Java HighLevel Rest Client, create a corresponding Bean in the startup class, and pass in the IP address of the ES client during initialization;

Finally, write the business processing Service layer.

  1. First prepare the request Request
  2. Then prepare the DSL, including query and request paging
  3. The third step is to send a request
  4. The fourth step is to analyze

The specific process of analysis is:

  1. Preliminary analysis of response.getHits()
  2. getTotalHits().value gets the total number of hits
  3. Then getHits() to get the document array
  4. Start traversing, getSourceAsString() to obtain the document source
  5. Then deserialize parseObject
  6. Finally put into the collection
  7. The final final package returns

Then, we expand the basic search and add filter conditions. For example, in terms of sorting, you can sort comprehensively, prioritize sales, speed, etc.; in promotions, you can select some daily activities; you can also select a price range, etc.

After clarifying the business, we do the specific code work:

  1. We modify the entity class corresponding to the passed parameters and add options for these fields.
  2. Then in the business logic, that is, the service layer, add the step of binding the query field during the DSL preparation stage.
    1. First build BoolQueryBuilder bool = new ~;
    2. Then add filter conditions:
      1. Determine whether the filter parameters in the incoming entity class are not empty, such as promotional activities params.getEvent()!=null && !params.getEvent().equals("");
      2. Once it is not empty, the built BoolQueryBuilder is constructed with filter conditions, that is, bool.filter(QueryBuilders.termQuery("event", params.getEvent());
      3. As for price filtering, the parameters in the filter are as follows: QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice())
    3. Finally, put it into the source of the query request, request.source().query(bool);

The second extension is to add the selection of nearby restaurants based on geographical location.

This can be done by adding sorting operations to the request and response respectively.

The third extension is to add store bidding ranking.

We use function_score query implementation, which includes three aspects to be determined:

  1. Filter conditions: Query those that meet the conditions and further calculate the scores.
  2. Fraction function: Calculate fractions for comparison. include
    1. weightUse weight
    2. random_score calculates random numbers
    3. field_value_factor takes a field value in the document as the function result
    4. script_score custom scoring function algorithm
  3. Operation mode: calculated score and original value. The original value is calculated based on word frequency, etc., and the operation is performed to obtain the final result. include
    1. multiply: multiply
    2. replace: replace query score with function score
    3. Others, such as: sum, avg, max, min

The three aspects we identify here are:

  1.  Filter condition: add isAD field, if true, perform weighted calculation
  2. Calculation function: weight
  3. Operation mode: default multiply

Code level changes,

  1. First add the isAD field in the entity class
  2. Then when binding filter conditions in DSL, add scoring, that is
    FunctionScoreQueryBuilder functionScoreQuery =
            QueryBuilders.functionScoreQuery(
            // 原始查询,相关性算分的查询
            boolQuery,
            // function score的数组
            new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                // 其中的一个function score 元素
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                    // 过滤条件
                    QueryBuilders.termQuery("isAD", true),
                    // 算分函数
                    ScoreFunctionBuilders.weightFactorFunction(10)
                )
            });
  3.  The final source is not bool, but the function of the package number.

5. How does the Neo4j database store data, what types of nodes and what types of routes are there?

Our nodes store institutions, which are divided into three types of labels: primary transfer center, secondary transfer center and node.

The attributes of the node include: Neo4j's own id, business id, name, phone number, address, coordinates, etc.

The relationship is stored as a route, and its attributes include its own ID and cost.

6. You talked about querying the shortest route and the lowest cost route. What is the Neo4j query language?

Neo4j statement:

Query the shortest

MATCH path = shortestPath((start:AGENCY) -[*..10]-> (end:AGENCY))
    WHERE start.bid = 123123 AND end.bid = 123456
    RETURN path

Lowest query cost

MATCH path = (start:AGENCY) -[*..10]->(end:AGENCY)
    WHERE start.bid = 123123 AND end.bid = 123456
    UNWIND relationships(path) AS r
    WITH sum(r.cost) AS cost, path
    RETURN path ORDER BY cost ASC, LENGTH(path) ASC LIMIT 1

Java statement:

Query the shortest

  1. Get the type of network
  2. Construct query statement
  3. Execute query
    1. Setting parameters
    2. Set response data type
    3. Encapsulate the results
      1. Read node data and enter the stream
        1. Take the first tag as the type
        2. Encapsulate latitude and longitude data
    @Override
    public TransportLineNodeDTO findShortestPath(AgencyEntity start, AgencyEntity end) {
        //获取网点数据在Neo4j中的类型
        String type = AgencyEntity.class.getAnnotation(Node.class).value()[0];
        //构造查询语句
        String cypherQuery = StrUtil.format("MATCH path = shortestPath((start:{}) -[*..10]-> (end:{}))\n" +
                "WHERE start.bid = $startId AND end.bid = $endId \n" +
                "RETURN path", type, type);

        //执行查询
        Optional<TransportLineNodeDTO> optional = this.neo4jClient.query(cypherQuery)
                .bind(start.getBid()).to("startId") //设置参数
                .bind(end.getBid()).to("endId")//设置参数
                .fetchAs(TransportLineNodeDTO.class) //设置响应数据类型
                .mappedBy((typeSystem, record) -> { //对结果进行封装处理
                    PathValue pathValue = (PathValue) record.get(0);
                    Path path = pathValue.asPath();
                    TransportLineNodeDTO dto = new TransportLineNodeDTO();
                    // 读取节点数据
                    List<OrganDTO> nodeList = StreamUtil.of(path.nodes())
                            .map(node -> {
                                Map<String, Object> map = node.asMap();
                                OrganDTO organDTO = BeanUtil.toBeanIgnoreError(map, OrganDTO.class);
                                //取第一个标签作为类型
                                OrganTypeEnum organTypeEnum = OrganTypeEnum.valueOf(CollUtil.getFirst(node.labels()));
                                organDTO.setType(organTypeEnum.getCode());
                                //查询出来的数据,x:经度,y:纬度
                                organDTO.setLatitude(BeanUtil.getProperty(map.get("location"), "y"));
                                organDTO.setLongitude(BeanUtil.getProperty(map.get("location"), "x"));
                                return organDTO;
                            })
                            .collect(Collectors.toList());
                    dto.setNodeList(nodeList);

                    //提取关系中的 cost 数据,进行求和计算,算出该路线的总成本
                    double cost = StreamUtil.of(path.relationships())
                            .mapToDouble(relationship -> {
                                Map<String, Object> objectMap = relationship.asMap();
                                return Convert.toDouble(objectMap.get("cost"), 0d);
                            }).sum();
                    dto.setCost(cost);

                    //取2位小数
                    dto.setCost(NumberUtil.round(dto.getCost(), 2).doubleValue());
                    return dto;
                }).one();

        return optional.orElse(null);
    }

The query cost is optimal, omitted

7. Does your project have both front-end and back-end? Do you know anything about the front-end?

On the front end, I have learned the basics of HTML, CSS, and JS, been exposed to some Vue and Ajax algorithms, and learned about the latest technologies such as ElementUI developed by Ele.me.

8. Your integer data prediction, what kind of prediction is this?

This is used to predict integer data. The fork is a part of the car, like a fork with only two heads. The initial shape accuracy of the fork produced from the molding machine is not yet up to par, and requires secondary shaping. Among them, the parameters of the machine are our input, and the integer deformation variable is our output. We use the measured data as training set samples in order to predict the deformation after inputting parameters.

9. I see you also did facial recognition. Did you do it yourself?

It was done by our team. I am the team leader and responsible for other modules. I know a little about face recognition.

This face recognition calls a trained model and is made with opencv. I still remember that the team members couldn't solve it, so I found the source code and showed it to them, and they completed the progress after reading it themselves.

10. Do you understand the kernel function?

learn. It is a mathematical function that can reduce high-dimensional data into low-dimensional results through the calculation of its mathematical function.

Kernel functions have many application scenarios, one of which is to replace the distance calculation function in SVM (Support Vector Machine) to facilitate data classification.

11.Do you know what kernel function SVM uses?

There are generally linear kernels, in addition to Gaussian kernels, Gaussian radial basis functions, Sigmoid kernels, etc.

12. What is the innovation point of the paper?

I combined two mainstream ideas in the field, bitmap marking and bitmap embedding, and used them in classic algorithms to achieve progress in the ability to embed secret information.

13.What are the basic data types of Java?

Four categories and eight species.

Barabara

14. Talk about the difference between == and equals

  • "==" is an operator. If it is a basic data type, comparethe stored value; if it is a reference data type, then Compares the address value of the object pointed to by .
  • equals is a method of Object. It compares the address value of the object pointed to by . Generally, after rewriting, the comparison is The value of the object.

 (Excerpted fromDetailed explanation of the difference between "==" and equals)

15.There are several types of Spring configuration files

3 types. properties, yml and yaml. The order of priority is:

properties>yml>yaml

In addition, there are two ways to set parameters,

One is Java system property configuration, in the format: -Dkey=value, which developers occasionally use. For example:

-Dserver.port=9000

There is also a command line parameter in the format: --key=value, which is often used by testers. For example:

--server.port=10010

 To summarize, there are 3 configuration files.

In addition, these three configuration files, plus 5 ways to set parameters, have the following priorities (from low to high):

  • application.yaml (ignored)
  • application.yml (enterprise utility)
  • application.properties
  • java system properties (-Dxxx=xxx)
  • Command line parameters (--xxx=xxx) (useful for testers)

16. What is the difference between StringBuilder and StringBuffer, and how is their efficiency compared?

StringBuilder is thread-unsafe and faster than the latter;

StringBuffer is thread-safe and slower than the former;

When concatenating strings, it is faster than String.

17. What should I do if I want to get the path of the current folder in Linux?

pwd

18. Have you deployed any projects? Which projects have you deployed?

We use Docker for project deployment.

Docker is a container management tool that can separately encapsulate the environment in which a certain component, such as MySQL, needs to be run, and run it on Linux, so that it can be easily deployed and used.

First install Docker. I won’t talk about the image source and so on. Just do it directly.

yum install -y docker-ce

Turn off the firewall, systemctl start docker, and docker -v to check the version. If there is no problem, it will be installed.

Then pull the image, such as pulling mysql, directly

docker pull mysql:latest

19.Do you know Python’s Pytest framework?

20. Have you ever written an interface service? How do the backend and frontend interact?

Wrote.

The front-end renders the page, and the user operates the page through the browser. Different operations send HTTP requests to the back-end server. The server responds to these requests, processes business, searches the database, and returns the response results to the front-end.

21.What has the database been used for?

have. I have used relational database MySQL, non-relational database MongoDB, Neo4j, etc.

22.How to query MySQL classification query

group by

23. If I want to copy a table, how should I write it? What if I want to delete/create it?

copy:

create table Table1 select * from Table2

delete:

drop table table 1

create:

create table 表1 if not exists

24. Have you ever written a more complex query? What does a complex query look like?

Wrote. Complex queries usually involve multiple tables and require flexible use of internal and external joins. For example, if there are two tables table1 and table2, and the connected field is id, then they are written as follows:

select * from table1 as t1 inner join table2 as t2 on t1.id = t2.id where 条件1, 条件2

25. We do not separate the front and back ends here. Can you write?

Guess you like

Origin blog.csdn.net/m0_46948660/article/details/133743941